JMenu ActionListener Example
This JMenu example shows how to enable a program to react to the user selecting a menu item. An ActionListener is added to the "exit" menu item.
When it is selected the code in the actionPerformed() method arranges for the frame to be disposed and the program to exit.
Normally a listener would be associated with each menu item.
//JMenu ActionListener Example
import java.awt.event.*;
import javax.swing.*;
class JMenuActionListenerExample {
public static void main(String[] args) {
final JFrame frame = new JFrame();
JMenu menu = new JMenu("File");
menu.add(new JMenuItem("New"));
menu.add(new JMenuItem("Open"));
menu.add(new JSeparator());
menu.add(new JMenuItem("Save"));
menu.add(new JMenuItem("Save as..."));
menu.add(new JSeparator());
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
frame.dispose();
System.exit(0);
}
});
menu.add(exit);
JMenuBar bar = new JMenuBar();
bar.add(menu);
frame.setJMenuBar(bar);
frame.setSize(150,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
