This section contains the detail about the creating menus using Swing in java.
Working with menus
A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-down menu. A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus.
In Java Swing, we use three objects to implement a menubar :
- JMenuBar
- JMenu
- JMenuItem
Example :
package corejava; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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 MenuDemo extends JFrame { public MenuDemo() { setTitle("JMenuBar"); JMenuBar menubar = new JMenuBar(); ImageIcon icon = new ImageIcon("E:/ankit_tutorial/java/Flags/exit.png"); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenuItem fileClose = new JMenuItem("Close", icon); fileClose.setMnemonic(KeyEvent.VK_C); fileClose.setToolTipText("Exit application"); fileClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); file.add(fileClose); menubar.add(file); setJMenuBar(menubar); setSize(250, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new MenuDemo(); } }
Description of Code
The Following Code create a menubar :
JMenuBar menubar = new JMenuBar();
Below code displays an icon in the menu :
ImageIcon icon = new ImageIcon("exit.png");
The following code creates a menu object and set keyboard shortcut for Menu :
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
The menus can be accessed via the keybord as well. To bind a menu to a particular key, we use the "setMnemonic" method. In our case, the menu can be opened with the ALT + F shortcut.
We sets the tooltip for menu item as :
fileClose.setToolTipText("Exit application");
Output :
[ 0 ] Comments