While developing well applications, a programmer needs input contrivance such as a menu. It will perform many actions that need to implement in the application. It can fetch the event actions that will help to the developer to perform. Swing Menu component hides the menu items, when click on the menu that displays menu items. Swing uses JMenuBar and the declaration of JMenuBar is as follows.
[java]public class JMenuBar
extends JComponent
implements Accessible, MenuElement[/java]
A developer can add radio boxes and check boxes, attach to the menu depends on the client requirements. The SPlessons tutorial will help users about how to create a menu and how to insert needed items.
Menu
Example
Below is the source code of Swing Menu which describes how to create the simple Swing Menu and adding the items to the menu.
MenuExample.java
[java]package swing;//create a package
import java.awt.EventQueue;//import all the required packages
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 MenuExample extends JFrame {//created a class that should extend JFrame
public MenuExample() {//created consructor
initUI();
}
private void initUI() {
createMenuBar();
setTitle("Menu");//set the title of the window
setSize(300, 200);//set the size of the window
setLocationRelativeTo(null);//to set the window in center of the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);//to close the windoe
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();//menu created
ImageIcon icon = new ImageIcon("quit.png");//quit image icon created
JMenu file = new JMenu("File");//object is created with JMenu class
file.setMnemonic(KeyEvent.VK_F);//depends on the keyboard actions
JMenuItem eMenuItem = new JMenuItem("Quit", icon);//menu item has been created with JMenuItem class
eMenuItem.setMnemonic(KeyEvent.VK_E);//keyboard events will be performed
eMenuItem.setToolTipText("Quit the application");//window will be closed.
eMenuItem.addActionListener(new ActionListener() {//added ActionListener to terminate the application
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(eMenuItem);
menubar.add(file);//menubar will have the file
setJMenuBar(menubar);
}
public static void main(String[] args) {//main method
EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe.
@Override
public void run() {
MenuExample ex = new MenuExample();
ex.setVisible(true);
}
});
}
}
[/java]
Create a class that should extend the JFrame, create a constructor that should be same as class name.
[java]public class MenuExample extends JFrame {
public MenuExample() {
}[/java]
Create the title, size,window termination method to an application.
[java]setTitle("Menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);[/java]
Create the object to the menu and create the object to the menu item.
[java]JMenu file = new JMenu("File");
JMenuItem eMenuItem = new JMenuItem("Quit", icon);[/java]
Add the menu item to the file and add file to the menu bar.
[java]file.add(eMenuItem);
menubar.add(file);//menubar will have the file[/java]
The invokeLater() method places the application on the Swing Event Queue.
[java]EventQueue.invokeLater(new Runnable())[/java]
Output:
After executing the above code successfully, the output will be as follows. When click on FILE, it displays the QUIT button, when click on the QUIT button then the application will be closed.
SubMenu
Example
This example describes about how to add menu items in the Swing Menu bar. Sub menu items will be use full to represent the look and feel of Windows as efficiently.
ExampleSubMenu.java
[java]package swing;//created a package
import java.awt.EventQueue;//import required packages
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class ExampleSubMenu extends JFrame {//created a class that should extend JFrame
public ExampleSubMenu() {//created a constructor
initUI();
}
private void initUI() {
createMenuBar();//create menubar
setTitle("Submenu");//title of the window
setSize(360, 250);//size of the window
setLocationRelativeTo(null);//to set the window in center of the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);//to close the window
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();//menubar has been created
ImageIcon iconNew = new ImageIcon("new.png");//created new box
ImageIcon iconOpen = new ImageIcon("open.png");//created open box
ImageIcon iconSave = new ImageIcon("save.png");//created save
ImageIcon iconExit = new ImageIcon("exit.png");//created exit
JMenu fileMenu = new JMenu("File");
JMenu impMenu = new JMenu("Import");//created import also
JMenuItem newsfMi = new JMenuItem("Import newsfeed list...");//click on import user get this i.e used JMenuItem class.
JMenuItem bookmMi = new JMenuItem("Import bookmarks...");//click on import user get this i.e used JMenuItem class.
JMenuItem mailMi = new JMenuItem("Import mail...");//click on import user get this i.e used JMenuItem class.
impMenu.add(newsfMi);
impMenu.add(bookmMi);
impMenu.add(mailMi);
JMenuItem newMi = new JMenuItem("New", iconNew);//created new icon with JMenuItem class
JMenuItem openMi = new JMenuItem("Open", iconOpen);//created open icon with JMenuItem class
JMenuItem saveMi = new JMenuItem("Save", iconSave);//created save icon with JMenuItem class
JMenuItem exitMi = new JMenuItem("Exit", iconExit);//created exit icon with JMenuItem class
exitMi.setToolTipText("Exit application");//application will be closed
exitMi.addActionListener(new ActionListener() {//ActionListener needs to be performed to close the application
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
fileMenu.add(newMi);//to add the elements
fileMenu.add(openMi);
fileMenu.add(saveMi);
fileMenu.addSeparator();
fileMenu.add(impMenu);
fileMenu.addSeparator();
fileMenu.add(exitMi);
menubar.add(fileMenu);//menubar will have the file menu
setJMenuBar(menubar);
}
public static void main(String[] args) {//main method
EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe.
@Override
public void run() {
ExampleSubMenu ex = new ExampleSubMenu();
ex.setVisible(true);
}
});
}
}[/java]
Create menu items that should open in menu bar.
[java]ImageIcon iconNew = new ImageIcon("new.png");
ImageIcon iconOpen = new ImageIcon("open.png");
ImageIcon iconSave = new ImageIcon("save.png");
ImageIcon iconExit = new ImageIcon("exit.png");[/java]
Create the import button and add items in to the import.
[java]JMenu impMenu = new JMenu("Import");
JMenuItem newsfMi = new JMenuItem("Import newsfeed list...");
JMenuItem bookmMi = new JMenuItem("Import bookmarks...");
JMenuItem mailMi = new JMenuItem("Import mail...");
[/java]
Add all the menu items to the file.When user click on file, menu items will be displayed.
[java]fileMenu.add(newMi);
fileMenu.add(openMi);
fileMenu.add(saveMi);
fileMenu.addSeparator();
fileMenu.add(impMenu);
fileMenu.addSeparator();
fileMenu.add(exitMi);[/java]
Output:
After executing the above code successfully, the output will be as follows. Where file menu consists of sub menus, each will have its own functionality, import used to import the required files from the system.
PopMenu
Example
The basic functionality of POPUP is, it can create the object to the JFrame, Swing Menu items will be added to that object. When click anywhere in the window application then it displays the menu items.
PopMenuExample.java
[java]package swing;//create a package
import java.awt.EventQueue;//import all the required packages
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class PopMenuExample extends JFrame {//create a class that should extend JFrame
private JPopupMenu pmenu;
public PopMenuExample() {//create constructor
initUI();
}
private void initUI() {
createPopupMenu();
setTitle("PopupMenu");//create window title
setSize(300, 250);//create size
setLocationRelativeTo(null);//set the location of the window at center of the screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//to close the window
}
private void createPopupMenu() {
pmenu = new JPopupMenu();//JPopupMenu creates popup menu
JMenuItem maxMi = new JMenuItem("Maximize");//popup menu consists of JMenu items
maxMi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {//to determine the state of the frame
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
});
pmenu.add(maxMi);//menu items will be inserted into the pop up menu
JMenuItem exitMi = new JMenuItem("Exit");
exitMi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pmenu.add(exitMi);
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {//if user clicks on mouse, MouseEvent.BUTTON3 enables the popup for right click
pmenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe.
@Override
public void run() {
PopMenuExample pm = new PopMenuExample();//created object pm
pm.setVisible(true);//it should always be as true to visible the window.
}
});
}
}[/java]
Create the pop up menu and create the Swing Menu item that is Maximize and perform ActionListener. When user click on maximize button then window will be maximized.
[java]pmenu = new JPopupMenu();
JMenuItem maxMi = new JMenuItem("Maximize");
maxMi.addActionListener(new ActionListener()[/java]
Create the EXIT button and add ActionListener to the exit button.When user click on the exit button window application will be closed.
[java]JMenuItem exitMi = new JMenuItem("Exit");
exitMi.addActionListener(new ActionListener()[/java]
Add both Maximum and Exit buttons to the popup menu.
[java]pmenu.add(maxMi);
pmenu.add(exitMi);[/java]
Create the main method and create the object to the class.The invokeLater() method places the application on the Swing Event Queue.
[java]PopMenuExample pm = new PopMenuExample();
pm.setVisible(true);
EventQueue.invokeLater(new Runnable() [/java]
Output:
After executing the above code successfully, the output will be as follows.In that frame, when give the right click on the window it displays popup items such as maximize and exit, when click on maximize then it will be maximized and click on exit it will be closed.
CheckBoxMenu
Example
While developing the applications, selecting the required inputs are mandatory, to select or deselect the items, check boxes will be useful. The following code describes how check box functionally flows.
CheckBoxMenu.java
[java]swing;//created a package with the name swing
import java.awt.BorderLayout;//import all the required packages
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class CheckBoxMenu extends JFrame {//create a class that should extend JFrame
private JLabel statusbar;//statusbar is JLabel component
public CheckBoxMenu() {//created constructors
initUI();
}
private void initUI() {
createMenuBar();
statusbar = new JLabel("Ready");//statusbar created
statusbar.setBorder(BorderFactory.createEtchedBorder());
add(statusbar, BorderLayout.SOUTH);//direction of the status box created
setTitle("JCheckBoxMenuItem");//created title
setSize(360, 250);//created size
setLocationRelativeTo(null);//to set the location of the window on the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);//to close the application
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
JCheckBoxMenuItem sbarMi = new JCheckBoxMenuItem("Show statubar");//JCheckBoxMenuItem creates the menu item list.
sbarMi.setMnemonic(KeyEvent.VK_S);
sbarMi.setDisplayedMnemonicIndex(5);//setDisplayedMnemonicIndex i.e to choose which one is going to be underlined
sbarMi.setSelected(true);
sbarMi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
statusbar.setVisible(true);
} else {
statusbar.setVisible(false);
}
}
});
viewMenu.add(sbarMi);
menubar.add(fileMenu);
menubar.add(viewMenu);
setJMenuBar(menubar);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CheckBoxMenu ex = new CheckBoxMenu();
ex.setVisible(true);
}
});
}
}[/java]
Create the status bar and write the method to place the status bar on the window.
[java]statusbar = new JLabel("Ready");//statusbar created
statusbar.setBorder(BorderFactory.createEtchedBorder());
add(statusbar, BorderLayout.SOUTH);[/java]
Create the File menu, View menu and set the Mnemonics that depends on the keyboard operation.
[java]JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);[/java]
Create the check box menu item and add ActionListener to the check box.
[java]JCheckBoxMenuItem sbarMi = new JCheckBoxMenuItem("Show statubar");
sbarMi.setMnemonic(KeyEvent.VK_S);
sbarMi.setDisplayedMnemonicIndex(5);
sbarMi.setSelected(true);
sbarMi.addItemListener(new ItemListener()[/java]
Add the menu items into the menu bar,when user click on view it displays status bar i.e is Ready.
[java]viewMenu.add(sbarMi);
menubar.add(fileMenu);
menubar.add(viewMenu);
setJMenuBar(menubar);[/java]
Output:
After executing the above code successfully, the output will be as follows. Where the window has file and view, when click to view it displays the status bar, if it is enabled then it shows ready at the bottom of the window.