Search code examples
javaswingjlistpopupmenu

One Java Swing PopupMenu for different JLists vs One Menu per JList


I created a popup Menu with 2 menu items : Edit and Remove. And then, I added this menu to 2 different JLists.

The result of clicking Edit or Remove is different between JLists, because they refer to different objects (Remove Menu Item: One should remove one object from an array and the other should remove a different object from a different array).

I'm wondering which is the best way to do it, performance or "good-coding" wise. Create a different popup menu for each component or use the same popup menu?

I am using the following code to find out which JList it is:

JPopupMenu popupMenu = new JPopupMenu("Menu");
addPopup(listShowSources, popupMenu);
addPopup(listShowESS, popupMenu);


JMenuItem menuItemEdit = new JMenuItem("Edit");
popupMenu.add(menuItemEdit);

JMenuItem menuItemRemove = new JMenuItem("Remove");
popupMenu.add(menuItemRemove);
menuItemRemove.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseReleased(MouseEvent arg0) {
        Component c = (Component)arg0.getSource();
        JPopupMenu popup = (JPopupMenu)c.getParent();
        JList<String> list = (JList <String> )popup.getInvoker();
        System.out.println(list.getName());
    }
});

With this code, I'll be creating instances of Popup menus and lists every time I press the button. Is this the "best" way to do this or should I just make 2 different popup menus?

Thank you for the help, Nhekas


Solution

  • One should remove one object from an array and the other should remove a different object from a different array).

    You should not be using Arrays.

    Swing uses a modified Model-View-Controller (MVC) design. Basically this means that the data display in the JList must be contained in the ListModel. So if you want to change the JList you change the ListModel.

    So there is no need for the array (i.e. you don't want to keep the data in two places). The DefaultListModel has methods that allow you to update the model directly.

    So your basic code is correct in that you get the invoker of the popup. So now all you need to do is get the DefaultListModel:

    DefaultListModel model = (DefaultListModel)list.getModel();
    model.remove(...);