Performing an action when an JMenuItem is clicked?

前端 未结 5 1688
挽巷
挽巷 2021-01-23 02:17

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

相关标签:
5条回答
  • 2021-01-23 02:24

    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.

    0 讨论(0)
  • 2021-01-23 02:27

    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().

    0 讨论(0)
  • 2021-01-23 02:28

    Give an instance of Action (extend from AbstractAction) to JMenuItem

    0 讨论(0)
  • 2021-01-23 02:40

    Based on the code you posted it looks like it should work, but we can't see the entire context of how the menu item is being used.

    Did you debug your code (with a System.out.println) to see if the ActionListener is being invoked?

    If you need more help post your SSCCE that demonstrates the problem.

    0 讨论(0)
  • 2021-01-23 02:45

    Fixed it.

    Forgot to add the actionPerformed method.

    0 讨论(0)
提交回复
热议问题