public class MainWindow extends JPanel {
public static MainWindow instance = new MainWindow();
private CardLayout cards = new CardLayout();
public MainWindow() {
setLayout(cards);
add(new FirstPage(), Pages.FIRST.toString());
add(new SecondPage(), Pages.SECOND.toString());
add(new ThirdPage(), Pages.THIRD.toString());
}
public void showPage(Pages page) {
cards.show(this, page.toString());
}
}
the showPage(page);
method works fine if I call it in the constructor of MainWindow
. But when I try to call MainWindow.instance.showPage(Pages.SECOND);
from an ActionListener in FirstPage
nothing happens. I've checked that the showPage(page)
method works correctly. I've checked that the ActionEvent is fired and enters the correct if/else clause. What am I doing wrong, why isn't my second page showing?
public class FirstPage extends JPanel {
private JButton showSecond = new JButton("Show Second");
private JButton showThird = new JButton("Show Third");
public FirstPage() {
insertButton(showSecond);
insertButton(showThird);
}
private void insertButton(JButton button) {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showSecond) {
MainWindow.instance.showPage(Pages.SECOND);
} else {
MainWindow.instance.showPage(Pages.THIRD);
}
}
});
this.add(button);
}
}
It would suggest a reference issue.
public static MainWindow instance = new MainWindow();
looks suspicious, as you would have had to create an instance ofMainWindow
first for it to be initialise which suggests you now have two instances ofMainWindow
, one on the screen and one that is notUsing
static
in this way is a bad idea, as it leads to issues like this. Instead you should pass a reference of the controller to the page. The controller would define the actions that each page could perform (and if done right, would be defined as aninterface
)Alternatively, you could separate the navigation from the pages into a separate mechanism, this means the pages don't care and can simply displayed in any order you want or reused else where
Example #1 - Controller based pages
This examples defines a simple controller which the pages can call in order to effect the navigation of the pages
Example #2 - central controller example
This example separates the controller from the pages, so that the buttons are not part of the pages themselves. This frees up the pages/views to be anything you need them to be
Example #3 - Model based
Or you could use a model based approach (which is probably more preferable), which defines the order in which components are displayed. For example