Swing - SPLessons

Swing Menu

Chapter 9

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Menu

Swing Menu

shape Description

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.

public class JMenuBar
   extends JComponent
      implements Accessible, MenuElement

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.

shape 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

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);
            }
        });
    }
}

Create a class that should extend the JFrame, create a constructor that should be same as class name.

public class MenuExample extends JFrame {
 public MenuExample() {
}

Create the title, size,window termination method to an application.

setTitle("Menu");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

Create the object to the menu and create the object to the menu item.

JMenu file = new JMenu("File");
JMenuItem eMenuItem = new JMenuItem("Quit", icon);

Add the menu item to the file and add file to the menu bar.

file.add(eMenuItem);
        menubar.add(file);//menubar will have the file

The invokeLater() method places the application on the Swing Event Queue.

EventQueue.invokeLater(new Runnable())

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.

shape 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

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);
            }
        });
    }
}

Create menu items that should open in menu bar.

ImageIcon iconNew = new ImageIcon("new.png");
        ImageIcon iconOpen = new ImageIcon("open.png");
        ImageIcon iconSave = new ImageIcon("save.png"); 
        ImageIcon iconExit = new ImageIcon("exit.png");

Create the import button and add items in to the import.

JMenu impMenu = new JMenu("Import");
JMenuItem newsfMi = new JMenuItem("Import newsfeed list...");
JMenuItem bookmMi = new JMenuItem("Import bookmarks...");
JMenuItem mailMi = new JMenuItem("Import mail...");

Add all the menu items to the file.When user click on file, menu items will be displayed.

fileMenu.add(newMi);
        fileMenu.add(openMi);
        fileMenu.add(saveMi);
        fileMenu.addSeparator();
        fileMenu.add(impMenu);
        fileMenu.addSeparator();
        fileMenu.add(exitMi);

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

shape 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

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.
            }
        });
    }
}

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.

pmenu = new JPopupMenu();
JMenuItem maxMi = new JMenuItem("Maximize");
        maxMi.addActionListener(new ActionListener()

Create the EXIT button and add ActionListener to the exit button.When user click on the exit button window application will be closed.

JMenuItem exitMi = new JMenuItem("Exit");
        exitMi.addActionListener(new ActionListener()

Add both Maximum and Exit buttons to the popup menu.

pmenu.add(maxMi);
pmenu.add(exitMi);

Create the main method and create the object to the class.The invokeLater() method places the application on the Swing Event Queue.

PopMenuExample pm = new PopMenuExample();
                pm.setVisible(true);
EventQueue.invokeLater(new Runnable() 

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

shape 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

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);
            }
        });
    }
}

Create the status bar and write the method to place the status bar on the window.

statusbar = new JLabel("Ready");//statusbar created
        statusbar.setBorder(BorderFactory.createEtchedBorder());
        add(statusbar, BorderLayout.SOUTH);

Create the File menu, View menu and set the Mnemonics that depends on the keyboard operation.

JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
 
        JMenu viewMenu = new JMenu("View");
        viewMenu.setMnemonic(KeyEvent.VK_V);

Create the check box menu item and add ActionListener to the check box.

JCheckBoxMenuItem sbarMi = new JCheckBoxMenuItem("Show statubar");
        sbarMi.setMnemonic(KeyEvent.VK_S);
        sbarMi.setDisplayedMnemonicIndex(5);
        sbarMi.setSelected(true);
        sbarMi.addItemListener(new ItemListener()

Add the menu items into the menu bar,when user click on view it displays status bar i.e is Ready.

viewMenu.add(sbarMi);
 
        menubar.add(fileMenu);
        menubar.add(viewMenu);
 
        setJMenuBar(menubar);

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.

Summary

shape Key Points

  • fileMenu.addSeparator(); separates Swing Menuitems.
  • JPopupMenu() creates popup Swing Menu.
  • setLocationRelativeTo(null>); is use full to set the location of the frame on the screen.