previous_developer
previous_developer

Reputation: 10988

Create jpanel in actionperformed listener?

I have 1 JFrame and 10 JPanel components as seperate classes. There is also JMenuBar on jframe. When a menu item clicked, i remove all content of contentPane of jframe (removeAll) and add one of my jpanels.

Here is my code;

// this function changes panel
public static void SwitchPanel(Component comp)
{
    Container panel = getContentPane();
    panel.removeAll();

    panel.add(comp);
    panel.revalidate();
    panel.repaint();
}

// this function defines menu items and their listeners
public JMenuItem AddMenuItem(JMenu menu, String name, final JPanel toPanel) {
    JMenuItem menuItem = new JMenuItem(name);
    menu.add(menuItem);

    menuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            SwitchPanel(toPanel);
        }
    });

    return menuItem;
}

and i add menu items like that;

AddMenuItem(menu1, "some menu item", new MyPersonalJPanel());

Everything works. BUT i want to create new jpanel when a related menu item clicked. I mean create jpanel if only it is necessary. Current code creates all jpanels first. When i clicked a menu item, shows me jpanel created before.

I think it can be done with Class.forName method, but i couldn't figure it out. Any help?

Upvotes: 1

Views: 1486

Answers (1)

Guillaume
Guillaume

Reputation: 5555

You should do the new MyPersonalJPanel() in the public void actionPerformed(ActionEvent e) method. That way the panel would be created each time the user click on the menu.

Your code would then be:

// this function defines menu items and their listeners
public JMenuItem AddMenuItem(JMenu menu, String name) {
    JMenuItem menuItem = new JMenuItem(name);
    menu.add(menuItem);

    menuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            SwitchPanel(new MyPersonalJPanel());
        }
    });

    return menuItem;
}

Upvotes: 1

Related Questions