有人可以解释以下原因为何无法达到我的预期吗?
按下按钮“应该”将导致显示中仅包含(空)JScrollPane,即输入字段和按钮应消失。但是,它们会一直保留到调整组件大小为止。
public static void main(String[] args) { JFrame frame = new JFrame("test"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); final JPanel panel = new JPanel(); Container cp = frame.getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JScrollPane(panel)); Component textField = new JTextField("i am input"); JButton button = new JButton(new AbstractAction("i am pressy") { @Override public void actionPerformed(ActionEvent e) { // this is already on the EDT panel.removeAll(); panel.revalidate(); } }); panel.setLayout(new FlowLayout()); panel.add(textField); panel.add(button); frame.pack(); frame.setVisible(true); }
谢谢你的帮助。p。
更新可见的GUI时,代码应为:
panel.revalidate(); panel.repaint(); // sometimes needed, this appears to be one of them