Reputation: 1540
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
Reputation: 168815
Use a CardLayout, as shown here.
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
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