Search code examples
javauser-interfaceborder-layout

Dynamically altering a BorderLayout in Java


I have a window with a BorderLayout, with a JPanel containing stuff put on CENTER, and a size of 800*250. I want that at the click of a button, that JPanel moves to NORTH and another JPanel gets to be on CENTER. I tried this, but it only resized my window without doing anything else.

I tried this but it doesn't seem to work.

public void actionPerformed(ActionEvent e) {
            frame.setPreferredSize(new Dimension(800,550));
            frame.removeAll();
            frame.add(northpanel, BorderLayout.NORTH);
            frame.add(southpanel, BorderLayout.CENTER);
            frame.getContentPane().repaint();
            frame.getContentPane().revalidate();
            frame.pack();
        }

northpanel was before set on CENTER.

Thank you. :)


Solution

  • The add() and remove() methods are overriden so they do everything automatically on the content pane. Remember the JFrame is just a container, everything that matters is your content pane. The removeAll() method is not overriden like that. What you should do is:

    frame.getContentPane().removeAll();
    

    You can read more on the Oracle website :)

    Using Top-Level Containers