我是Java的新手,我對面板有問題。我的程序中有一個JFrame
和兩個JPanels
。一個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);
}
}
請提供我們可以編譯的代碼片段。至少要描述你的當前代碼到底是什麼問題。 – ARRG 2012-02-22 11:48:06
請了解java的命名約定並堅持他們 – kleopatra 2012-02-22 14:00:52