From what I see you use a lot of "extending" that I don't think is necessary. Your code works but it could have been simpler.
First don't use the "dispose" method.
Second you need to close the the MainPage and open the PageOne.
To do that you need to call the setVisible(false) on the MainPage that is open. In order to have access to the original MainPage that you opened you need to pass it as parameter to the MapLabel.
But MapLabel is called from the MainPagePanel so that also needs to have it as parameter:
MapLabel class
MainPage mp;
public MapLabel(Icon icon, String name, MainPage mp) {
this.mp = mp;
}
// AT THE LISTENER:
......
PageOne po = new PageOne();
mp.setVisible(false); // disposing PageOne
// mp = new MainPage(); // you don't need that. It will create a new MainPage and overwrite the existing one.
// you have already created a MainPage, don't create another
But in order to call this:
public MapLabel(Icon icon, String name, MainPage mp) you need:
MainPagePanel class
MainPage mp;
public MainPagePanel(MainPage mp) {
Toolkit kit = Toolkit.getDefaultToolkit();
image = new ImageIcon("menu1.jpg");
this.mp = mp;
display = new MapLabel(image, "Display", mp);
And now to pass the MainPage that is opened as paramater
MainPage class
public MainPage() {
super("Test");
setSize(180,100);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// "this" is a MainPage. This MainPage that you just created and has all your Panels and labels
mpp = new MainPagePanel(this);
Container pane = getContentPane();
pane.add(mpp);
setContentPane(mpp);
setResizable(false);
setVisible(true);
}
With that way, "this", is in all the other Panels and Labels and they have access to the
same MainPage that you just opened.
Now that you have it inside you can pass it to the
PageOne class and after you are done the PageOne can set it back to visible true while setting itself to false:
class PageOne
class PageOne {
MainPage mp;
public PageOne(MainPage mp) {
this.mp = mp;
}
....
...
// in some method:
{
this.setVisble(false); //hiding PageOne
mp.setVisible(true);
}
}
It is better to call dispose on the PageOne:
mp.setVisible(true);
this.dispose();
Because you created it locally inside the Label and no one else has access to it, so if it is disposed no one will be affected by it.
Also whenever you call "Display" you create a new one, so if you set it to visible false, you will keep creating new PageOne objects that afterward will be simply not visible.
If you had it as a private property of the class and you simply changed its values (not create a new one) thetn it would be OK