Java Menu Example
Chapter:
Miscellaneous
Last Updated:
14-10-2016 10:10:37 UTC
Program:
/* ............... START ............... */
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JavaMenuExample extends JFrame {
public JavaMenuExample() {
initUI();
}
private void initUI() {
createMenuBar();
setTitle("Simple menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener((ActionEvent event) -> {
System.exit(0);
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JavaMenuExample ex = new JavaMenuExample();
ex.setVisible(true);
});
}
}
/* ............... END ............... */
Output
Notes:
-
A menu provides a space-saving way to let the user choose one of several options.
- Menus are unique in that, by convention, they aren't placed with the other components in the UI. Instead, a menu usually appears either in a menu bar or as a popup menu. A menu bar contains one or more menus and has a customary, platform-dependent location — usually along the top of a window.
Tags
Menu Example, Swing, Miscellaneous