Overlapping JPanel layout

I have a JPanel "mainPanel" that I want to add and remove other JPanels to, when a user changes from screen to screen. Right now I have it set up so that mainPanel has a 1x1 GridLayout,

JPanel mainPanel =new JPanel();

GridLayout gridLayout =new GridLayout();

gridLayout.setRows(1);

gridLayout.setColumns(1);

mainPanel.setLayout(gridLayout);

JPanel currentScreen =new JPanel();

mainPanel.add(currentScreen,null);

mainPanel.setVisible(true);

JPanel newScreen =new JPanel();

mainPanel.setVisible(false);

publicvoid getScreen(JPanel new_Screen){

currentScreen.setVisible(false);

mainPanel.add(new_Screen,null);

}

This successfully hides the currentScreen, but adds a new GirdLayout cell, making each JPanel take up 50% of the mainPanel (whereas I want newScreen to take up the entire mainPanel).

So I tried the following,

publicvoid getScreen(JPanel new_Screen){

mainPanel.remove(currentScreen);

mainPanel.add(new_Screen,null);

}

Which doesn't do anything, currentScreen is the only thing left showing.

So I changed it to this,

publicvoid getScreen(JPanel new_Screen){

mainPanel.remove(currentScreen);

mainPanel.repaint();

mainPanel.add(new_Screen,null);

}

and now the mainPanel is completely blanked out. This is all counterintuitive to me, and seems like it should be an easy problem to overcome.

Is there a better way of doing this?

I briefly tried making mainPanel a JLayeredPane instead of JPanel but it wasn't working for me...

I want the added JPanels to take up 100% of mainPanel, and simply make the one I want to see visible. Is there a layout I'm missing that will allow this?

[2517 byte] By [torfua] at [2007-11-26 23:37:19]
# 1
Ok I think I understand now after RTFMing a second time...Using BorderLayout, and setting components to BorderLayout.CENTER replaces the previous panel I stuck there and causes it to take up the whole container unless I set it otherwise.Perfect :)
torfua at 2007-7-11 15:00:39 > top of Java-index,Desktop,Core GUI APIs...