Frage

I have got a JMenu, to which I add items using a for loop. The items are displayed correctly, however, I've got no idea how to add any kind of Listener to the objects created. I don't need a listener on every single item added to JMenu, I just need a Listener on the JMenu, which returns "name" of the object i clicked on.. So if the JMenu contains an item "song", it should return String "song", when i click the item through the JMenu.

My current code:

JPopupMenu popup = new JPopupMenu();
            remove = new JMenuItem("delete");
            copyURL = new JMenuItem("copy url");
            add = new JMenuItem("add");
            edit = new JMenuItem("edit");
            addto = new JMenu("add to");
            popup.add(add);
            popup.add(edit);
            popup.add(addto);
            popup.add(copyURL);
            popup.add(remove);

            for(String x:model.getPlaylist()){
                addto.add(x);
            }


            if(! gui.display.isRowSelected(row)){
                gui.display.changeSelection(row, column, false, false);
            }
            popup.show(e.getComponent(),e.getX(),e.getY());
            remove.addActionListener(this);
            copyURL.addActionListener(this);
            add.addActionListener(this);
            edit.addActionListener(this);
            addto.addActionListener(this);
            }}
War es hilfreich?

Lösung

You can create your own action:

interface PlaylistListener {
    void addToPlaylist(String name);
}

class MainClass implements PlaylistListener {

    private void createJMenu() {
        addto = new JMenu("add to");
        //...
        for(String x: model.getPlaylist()){
            addto.add(new AddToPlaylistAction(x, this));
        }
        //...
    }

    @Override 
    void addToPlaylist(String name) {
        //...
    }
}

class AddToPlaylistAction extends AbstractAction {
    private String name;
    private PlaylistListener callback;

    public AddToPlaylistAction(String name, PlaylistListener callback) {
                    super(name);
        this.name = name;
        this.callback = callback;
    }

    void actionPerformed(ActionEvent e) {
        callback.addToPlaylist(name);
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top