You may use frame.remove()
The difference is that you may remove a whole panel instead of removing "several" things, and you just replace it with a new panel
frame.add( mainPanel );
...
// in the action listener
frame.remove( mainPanel );
frame.add( theNewPage );
The point is, you don't have to be afraid of removing awkwardly things in the main frame, for you have to place all those things into a single panel and then just change panels.
UPDATE
I've made the code needed to test what I'm talking about.
Here's a running sample:
later
Here's the running sample:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ChangePage {
JComponent mainPage;
JComponent newPage;
JFrame frame;
public static void main( String [] args ) {
ChangePage changePageDemo = new ChangePage();
changePageDemo.show();
}
private void show(){
frame = new JFrame("Demo");
frame.add( getMainPage() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
private JComponent getMainPage() {
if( this.mainPage != null ) {
return this.mainPage;
}
this.mainPage = new JPanel(new BorderLayout());
mainPage.add( new JLabel("Choose an option") );
mainPage.add( new JPanel(){{
add( new JButton("New"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
frame.remove( getMainPage() );
frame.add( getNewPage() );
//frame.setContentPane( getNewPage() );
frame.pack();
}
});
}
});
}});
add( new JButton("Options"));
add( new JButton("Exit"));
}}, BorderLayout.SOUTH );
return this.mainPage;
}
private JComponent getNewPage() {
if( newPage != null ) {
return newPage;
}
this.newPage = new JPanel();
this.newPage.add( new JLabel("<html>This is the \"new\" page.<br> Do you like it?<br></html>"));
this.newPage.add( new JButton("Return"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
frame.remove( getNewPage() );
frame.add( getMainPage() );
//frame.setContentPane( getMainPage() );
frame.pack();
}
});
}
});
}});
return this.newPage;
}
}
Alternatively you may use setContentPane
:)