William Pfaffe William Pfaffe - 7 months ago 14
Java Question

Getting the text from a JMenuItem that is pressed?

Currently using SWING to implement a JMenuBar, where there are 2 different JMenus. One is called gameMenu, and one is called, addMenuGame.

I have several JMenuItems in gameMenu, which are all implemented with this method, in my interface controller.

public void addGameMenu(JMenu control) {
String fileName = "gamemodes.txt";
try {

FileReader inputFile = new FileReader(fileName);

BufferedReader bufferReader = new BufferedReader(inputFile);

String line;

while ((line = bufferReader.readLine()) != null) {

String split[] = line.split("#");
for (int i = 0; i < split.length; i++) {
control.add(split[i]);
}

}

bufferReader.close();
} catch (Exception e) {
System.out.println("Fejl ved linje:" + e.getMessage());
}

}


what it does, is read every line from a text file, and adds that to the JMenu, called gameMenu. However, I can only add actionlisteners to the JMenu, and not the JMenuItem, that is of JMenu. In the JFrame main void, this is how I implement it:

public class index extends javax.swing.JFrame {

QuizzControlHandler dd = new QuizzControlHandler();
private JMenuItem dc;

/**
* Creates new form index
*/
public index(){

initComponents();
dd.addGameMenu(menuGame);

}

}


This will fill my menu correctly, however, I need to retrieve what the user is clicking on.

Answer

However, I can only add actionlisteners to the JMenu, and not the JMenuItem,

The user clicks on the JMenuItem so you need to add the ActionListener to the JMenuItem NOT the JMenu.

Before you invoke the addGameMenu(...) you can create an ActionListener to be shared by all the JMenuItems with code like:

ActionListener al = new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JMenuItem menuItem = (JMenuItem)e.getSource();
        System.out.println(menuItem.getText());
    }
}

Then you would change your addGameMenu(JMenu control, ActionListener al) to have a second parameter.

Then in the method you change:

//control.add(split[i]);
JMenuItem menuItem = new JMenuItem( split[I] );
menuItem.addActionListener( al );
control.add( menuItem );
Comments