Performing an action when an JMenuItem is clicked?

15,804

Solution 1

Suggestion: Instead of adding a separate ActionListener, just use AbstractAction:

JMenuItem fileExit = new JMenuItem(new AbstractAction("Exit Program") {
    public void actionPerformed(ActionEvent ae) {
        JFrame hello = new JFrame("POPUP");
        hello.setSize(100,75);
        hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);
        hello.setVisible(true);
    }
});

I'd also suggest, instead of setting EXIT_ON_CLOSE on the popup menu, you set it on the main frame of your application, and have the action simply call theMainFrame.dispose().

Solution 2

You got it working, but you have another problem.

Don't do this:

hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);

When you close the pop-up frame, your entire JVM terminates. Consult JFrame.setDefaultCloseOperation javadocs for a more appropriate value.

Share:
15,804
TheQuizitor
Author by

TheQuizitor

Updated on July 23, 2022

Comments

  • TheQuizitor
    TheQuizitor almost 2 years

    So i have made a simple program with a basic menu at the top of the frame, Now i just need to put actions behind each JMenuItem. Im struggling to work the code out though, Here is what i thought would work:

    JMenu file_Menu = new JMenu("File");
    JMenuItem fileExit = new JMenuItem("Exit Program"); 
    file_Menu.add(fileExit);
    fileExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFrame hello = new JFrame("POPUP");
            hello.setSize(100,75);
            hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);
            hello.setVisible(true);
        }
    });
    main_Menu.add(file_Menu);
    

    This doesn't seem to work though, I thought that this code would create a small popup window when the menu item is clicked.

    Can any spot the bug because i cant seem to.