I usually don’t need to ask Java questions, but I’m stuck more than ever on something now and I think I’m just missing something over and over again..
I have a JFrame application that has a JMenuBar. The items in the menubar have my class PageManager as their ActionListener. Debug shows this all works fine. The whole lot is initialized like this:
public static void main(String[] args) {
UI ui = new UI(); //The JFrame
PageManager pm = new PageManager(ui); //Menu ActionListener
MenuBar mb = new MenuBar(pm); //MenuBar
ui.setJMenuBar(mb);
ui.setDefaultCloseOperation(0);
ui.setVisible(true);
ui.setPage(new Home().getPanel()); //a View
}
In the UI class, I have the following method:
public void setPage(JPanel p) {
System.out.println("Set page");
this.remove(page);
System.out.println("Removed");
this.add(p);
System.out.println("Added " + p);
}
The ui.setPage(new Home().getPanel()); method call works fine. If I move it to the constructor of PageManager, it works too. If I replace it with ui.setPage(new Preferences().getPanel());, it works too. The Home and Preferences classes are Views that create a JPanel and return it using the getPanel method.
However, changing the page using the actionlistener doesn’t seem to work. ALL System.out.println lines print fine, but the page isn’t changed. I use this in PageManager:
private void changePage(String s, int i) {
if(s.equals("P")) {
//Program options
System.out.println("program options");
if(i == 1) {
ui.setPage(pref.getPanel());
}
} else if(s.equals("C")) {
//Connection options
} else if(s.equals("A")) {
//Add rule
}
}
(ActionListener picks up the event, checks the source and calls changePage with it).
Thing is, everything runs and seems to work fine according to console output, but the page won’t change whatever I do (including small modifications).
Any help would be greatly appreceated!!!
Kind regards,
Mark
Normally to achieve such behaviour the easier way out is the use of CardLayout.
And Moreover, once you add a new panel to already existing JFrame, by removing the old one, try to
revalidate()andrepaint(), so that the new addition can be realized.If your JDK is 1.6 or below then revalidate on frame wont’ work, instead use
frameObject.getRootPane().revalidate();Here is one sample code snippet to help your cause, with JMenuBar added to it :