2

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 
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DanM
  • 1,530
  • 4
  • 23
  • 44

2 Answers2

4

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.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

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);
Adel Boutros
  • 10,205
  • 7
  • 55
  • 89