我有一个简单的任务。
有一个框架。那个框架里有两块镶板。在第二个面板上有一个按钮。当用户单击该按钮时,第一个面板必须更改其内容。
下面是代码:
package test;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
class MyJPanel1 extends JPanel {
MyJPanel1() {
this.add(new JButton("MyJPanel1"));
}
}
class MyJPanel2 extends JPanel {
MyJPanel2() {
this.add(new JButton("MyJPanel2"));
}
}
class MyFrame extends JFrame {
JPanel topPanel = null;
MyFrame() {
super("Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0, 1, 20, 20));
topPanel = new MyJPanel1();
this.add(topPanel);
JPanel bottomPanel = new JPanel();
this.add(bottomPanel);
JButton button = new JButton("switch");
button.addMouseListener(new MouseClickListener());
bottomPanel.add(button);
this.pack();
this.setVisible(true);
}
class MouseClickListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
topPanel = new MyJPanel2();
System.out.println("switch");
topPanel.invalidate();
topPanel.validate();
topPanel.repaint();
MyFrame.this.invalidate();
MyFrame.this.validate();
MyFrame.this.repaint();
}
}
}
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MyFrame();
}
});
}
}
但这不起作用。在我点击按钮后,我在控制台中看到文本,但第一个面板保持不变。我读到我必须使用invalidate() validate()和repaint()方法,我这样做了,但它没有帮助。
如果你想"切换"面板,那么你应该使用CardLayout
。CardLayout
允许2个(或更多)组件共享容器中的相同空间,但一次只能看到一个组件。
请阅读Swing教程中关于如何使用CardLayout的部分,了解更多信息和工作示例。
在mouseclick()方法中创建了一个新的topPanel,但是没有对它做任何操作。也许你想从myFrame中删除原来的topPanel,创建一个新的topPanel,然后将新的topPanel添加到myFrame中。
注意,这可能不是最好的策略(创建一个新的topPanel)。