views:

322

answers:

6

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.

A: 

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

Dmitry
A: 

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.

camickr
A: 

Fixed it.

Forgot to add the actionPerformed method.

TheQuizitor
You can make sure the superclass' overridden `actionPerformed` function is provided correctly by preceding it with `@Override`.
Paul Lammertsma
+1  A: 

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.

Noel Ang
Damn, your right. Lucky that was mentioned before i delved further into the development.Thanks.
TheQuizitor
A: 

So i got it working and now when i do click the JMenuItem an action is performed like i intended, but as the item is supposed to exit the program i thought that putting the code

System.exit(0);

Would just exit the software, but i recieve an error

Cannot find symbol
symbol  : method exit(int)
location: class System

The class i am using is called System. What could be my problem?

Apologies for all the questions.

TheQuizitor
It's best to ask this as a separate question than as the "answer" to an existing question.
Andrew Swan
A: 

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

David Moles