Search code examples
javaresizejpaneljlayeredpane

Dynamic GUI size


I have this problem with resizing some JPanels in a GUI application. The application has a main JLayeredPane which contains 2 other JPanels. In JPanel 1 I have a login form and a button. When I press the button I want to make the first JPanel invisible and the second JPanel visible (this panel is bigger than the first), but remains the same size. Bellow is some relevant code. Can anyone help me?

int width=300, height=300;
JLayeredPane mainPanel;
JPanel panel1;
JPanel panel2;

panel1.setBounds(0,0,width,height);
panel1.setBackground(new Color(251, 249, 236));
mainPanel.add(panel1, JLayeredPane.DEFAULT_LAYER);

panel2.setBounds(0, 0, width+200, height+200);
panel2.setBackground(new Color(255, 0, 0));
mainPanel.add(panel2, JLayeredPane.DEFAULT_LAYER);

And the clicked button code:

setSize(width+200, height+200);
    panel1.setVisible(false);
    panel2.setVisible(true);
    mainPanel.setSize(width+200, height+200);
    mainPanel.validate();
    mainPanel.repaint();

Here is some code for the JLayredPane:

GroupLayout mainLayout=new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);

        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, width, GroupLayout.PREFERRED_SIZE))
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, height, GroupLayout.PREFERRED_SIZE))
        );

LE:

for the button:

setSize(width+200, height+200);

        mainPanel.setSize(width+200, height+200);
        mainPanel.remove(panel1);
        mainPanel.remove(panel2);
        mainPanel.add(panel2, JLayeredPane.DEFAULT_LAYER);
        actualizare();
        mainPanel.validate();
        mainPanel.repaint();
        validate();
        repaint();

The function:

void actualizare(){
        GroupLayout mainLayout=new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);

        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, width+200, GroupLayout.PREFERRED_SIZE))
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, height+200, GroupLayout.PREFERRED_SIZE))
        );

    }

Solution

  • Try calling validate() and repaint() at the end.