Question

I have a GUI going in Netbeans.. The only problem that I have is to add events to my JMenuItems. I'm currently loading a String[] in as my menulist adding a new JMenuItem for .length

private void addToGamePanel(){
      String[] gameNames =  con.getGameNames();
      for (int i = 0; i < gameNames.length; i++) {
        jMenu2.add(new JMenuItem(gameNames[i]));

      }        
}

My problem is then how to add action events for the JMenuItem.. I cant set the event in the GUI window cause the Item is not made before the load of gameNames.

Was it helpful?

Solution

You have to pass each of your menu items an action listener. One possibility is to have your class implement the ActionListener interface and define the method actionPerformed.

class YourClass implements ActionListener {

    [...]

    private void addToGamePanel(){

        String[] gameNames =  con.getGameNames();
        for (int i = 0; i < gameNames.length; i++) {

            JMenuItem item = new JMenuItem(gameNames[i])
            item.addActionListener(this);
            jMenu2.add(item);
         }        
    }

    public void actionPerformed(ActionEvent e) {
        JMenuItem menuItem = (JMenuItem)(e.getSource());

        // do something with your menu item
        String text = menuItem.getText();

    }
}

In this case, your instance of the class also acts as the ActionListener. For simple things, you can also use an anonymous class

    private void addToGamePanel(){

        String[] gameNames =  con.getGameNames();
        for (int i = 0; i < gameNames.length; i++) {
            JMenuItem item = new JMenuItem(gameNames[i])
            item.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JMenuItem menuItem = (JMenuItem) e.getSource();
                    // do something with your menu item
                    String text = menuItem.getText();
                }
            });
            jMenu2.add(item);
         }
    }

If you have some more advanced needs, you might consider defining a separate ActionListener or even better an Action, have a look at: How to use Actions

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