Swing Menu Bar Example

This example shows how to create a simple Menu bar using Swing JMenuBar class.

A menu is a group of commands located in a menubar. A toolbar has buttons with some common commands in the application.

Swing JMenuBar Example

The following example demonstrates how to use the JMenuBar class to display menubar on the window or frame:
package net.sourcecodeexamples.swingexamples.menus;

import java.awt.EventQueue;
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 SimpleMenuExample extends JFrame {

    private static final long serialVersionUID = 1 L;

    private void initializeUI() {

        createMenuBar();

        setTitle("Simple menu");
        setSize(350, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createMenuBar() {

        JMenuBar menuBar = new JMenuBar();
        ImageIcon exitIcon = new ImageIcon("src/resources/exit.png");

        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);

        JMenuItem eMenuItem1 = new JMenuItem("Stop", exitIcon);
        eMenuItem1.setMnemonic(KeyEvent.VK_E);
        eMenuItem1.setToolTipText("Stop application");
        eMenuItem1.addActionListener((event) - > System.exit(0));

        JMenuItem eMenuItem = new JMenuItem("Exit", exitIcon);
        eMenuItem.setMnemonic(KeyEvent.VK_E);
        eMenuItem.setToolTipText("Exit application");
        eMenuItem.addActionListener((event) - > System.exit(0));

        fileMenu.add(eMenuItem);
        fileMenu.add(eMenuItem1);
        menuBar.add(fileMenu);

        setJMenuBar(menuBar);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() - > {
            SimpleMenuExample simpleMenuExample = new SimpleMenuExample();
            simpleMenuExample.initializeUI();
            simpleMenuExample.setVisible(true);
        });
    }
}

Output


Comments