DanM
DanM

Reputation: 1540

Switching JPanels in JFrame and back

I am switching on button click to new JPanel with the use of:

JPanel newP = new ProjectPage();
contentPane.revalidate(); 
setContentPane(newP);

Where ProjectPage is:

 public class ProjectPage extends JPanel

But how I create button in my new ProjectPage class that will take me back to my original panel?

My main screen class declared like so:

public class MainScreen extends JFrame 

Upvotes: 2

Views: 1925

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Use a CardLayout, as shown here.

Game view High Scores view

See How to Use CardLayout for details.

As more general advice, do not extend JPanel or JFrame, but simply keep references to them & build them as needed for each use. Part of this problem seems to be scope - the relevant panels are not 'visible' to the calling code. Keeping references to them in the main class is an easy solution to that.

Upvotes: 4

Adel Boutros
Adel Boutros

Reputation: 10285

If you want to go back to the original JPanel, you have to keep a reference of it somewhere in your class by adding a field private JPanel oldPanel;

When you create your new panel, get the old Panel and save it in that field like:

oldPanel = getContentPane();
JPanel newP = new ProjectPage();
contentPane.revalidate(); 
setContentPane(newP);

and when you want to go back to your original panel, you do:

setContentPane(oldPanel);

Upvotes: 2

Related Questions