我是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);
}
}
Run Code Online (Sandbox Code Playgroud)
BorderLayout每个约束只能处理一个组件,即在CENTER中添加p2的那一刻,p1被遗忘.所以要么删除/添加你的actionListeners,要么使用另一个LayoutManager,比如fi CardLayout.