I’m a newbie in Java and I have a problem regarding panels. I have one JFrame and two JPanels in my program.
- When I click
button1,panel1will show in the frame. - When I click
button2,panel2will show in the frame andpanel1will disappear/hide.
The problem is that panel1 can’t show only panel2. How to show the two panels in this way?
This is my code:
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);
}
}
BorderLayout can only handle one component per constraint, that is the moment you add p2 in CENTER, p1 is forgotten. So either do a remove/add in your actionListeners or use another LayoutManager, like f.i. CardLayout.