Search code examples
javaswingactionlistenerjmenujmenuitem

Add functionality to a menu button in java


I am new to Java and I was wondering how to add functionality to menu item?
What I would like it to do, is to set two values to 0.

This is the code I have currently:

JMenuItem clear = new JMenuItem("Clear");
Options.add(clear);

Solution

  • You will need to add an ActionListener. This is an interface which must implement a method called actionPerformed.

    E.g

    clear.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
          // Clear two values.
        }
    });`
    

    This will add an anonymous ActionListener that is invoked once the JMenuItem is clicked.

    Hope that helps.