Question

I am planning to make a program that in the top of the contentPane has a menubar.

Under this menubar another JPanel, here is what I did (it works), but I don't know if this is the best way:

I made a lot of JPanels with different buttons, I want that a JMenuItem changes the screen(JPanel)

So what I did for each JMenuItem that set the specific JPanel(all panels are in the same position in the GridBagLayout, but all start with .setVisible(false);)

jemnuitem1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        jpanelItem1.setVisible(true);
        jpanelItem2.setVisible(false);
        jpanelItem3.setVisible(false);
    }
});     

jemnuitem2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        jpanelItem1.setVisible(false);
        jpanelItem2.setVisible(true);
        jpanelItem3.setVisible(false);
    }
});     

jemnuitem3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        jpanelItem1.setVisible(false);
        jpanelItem2.setVisible(false);
        jpanelItem3.setVisible(true);
    }
});

This works, but I want to know if there is a way better to do this, or can I have a big problem doing this, because if this works, its fine for me work in this way, but I want the help of others that already made something similar.

Was it helpful?

Solution

You should use CardLayout. Then you can switch the visible panel instead of writing clumsy code like you have now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top