【发布时间】:2012-02-22 11:45:10
【问题描述】:
我是 Java 新手,我对面板有疑问。我的程序中有一个JFrame 和两个JPanels。
- 当我单击
button1时,panel1将显示在框架中。 - 当我单击
button2时,panel2将显示在框架中,panel1将消失/隐藏。
问题是panel1 不能只显示panel2。这两个面板如何显示?
这是我的代码:
public class test{
public static void main(String args[]){
JButton b1 = new JButton("show p1");
JButton b2 = new JButton("show p2");
JLabel l1 = new JLabel("This is p1");
JLabel l2 = new JLabel("This is p2");
final JPanel p1 = new JPanel(new FlowLayout());
p1.add(l1);
final JPanel p2 = new JPanel(new FlowLayout());
p2.add(l2);
JPanel buttonPNL = new JPanel(new FlowLayout());
buttonPNL.add(b1);
buttonPNL.add(b2);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
p1.setVisible(true);
p2.setVisible(false);
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
p1.setVisible(false);
p2.setVisible(true);
}
});
JFrame frm = new JFrame();
frm.setLayout(new BorderLayout());
frm.add(p1,BorderLayout.CENTER);
frm.add(p2,BorderLayout.CENTER);
frm.add(buttonPNL,BorderLayout.SOUTH);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setSize(300,300);
}
}
【问题讨论】:
-
请提供我们可以编译的代码sn-p。至少准确描述您当前代码的问题所在。
-
请学习java命名约定并遵守它们