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