I am trying to make the following layout where all JPanels are visible, with the exception of panel2, when the program starts. When the user presses btn1, then JCalendar and panel3 become invisible, and panel2 becomes visible. The problem I ran into is that panel2 is not showing with btn1 pressed. However, if I change the borderlayout of panel2 to one that is not used (in this case WEST), it will be displayed when the button is pressed, but it will align on the left side, and I want it to be centered in shape.
code:
public class GUI extends JFrame implements ActionListener, PropertyChangeListener { private JPanel panel1, panel2, panel3; private com.toedter.calendar.JCalendar calendar; private Button btn1, btn2; private JLabel label1, label2; public GUI() { init(); } private void init() { //panel1 components panel1 = new JPanel(); btn1 = new JButton("Click me"); panel1.add(btn1); //panel2 components panel2 = new JPanel(); label1 = new JLabel("Time:"); label2 = new JLabel("Date:"); panel2.add(label1); panel2.add(label2); //JCalendar calendar = new com.toedter.calendar.JCalendar(); //panel3 panel3 = new JPanel(); //Add panels to JFrame add(panel1, BorderLayout.NORTH); add(calendar, BorderLayout.CENTER); add(panel2, BorderLayout.CENTER); //if i set this to WEST it show!! add(panel3, BorderLayout.EAST); //event handling btn1.addActionListener(this); //hide panel2 panel2.setVisible(false); pack(); } public void actionPerformed(ActionEvent ae) { if(ae.getSource().equals(btn1) { calendar.setVisible(false); panel3.setVisible(false); panel2.setVisible(true); //make panel2 visible panel2.updateUI(); revalidate(); repaint(); } } public static void main(String args[]) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new GUI().setVisible(true); } }); }

When I press btn1, JCalendar and panel3 are invisible, but panel2 does not show

source share