JMenuBar in Java Swing

A JMenuBar in Java Swing is a graphical component used to create menus in a GUI application. Menus provide a convenient way to group and present various actions or options to users. Following is a basic example demonstrating the usage of JMenuBar:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

public class JMenuBarDemo extends JFrame {
    public JMenuBarDemo() {
        setTitle("JMenuBar Demo");

        // Create the menu bar
        JMenuBar menuBar = new JMenuBar();

        // Create a menu
        JMenu fileMenu = new JMenu("File");

        // Create menu items
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem exitItem = new JMenuItem("Exit");

        // Add menu items to the menu
        fileMenu.addSeparator(); // Add a separator

        // Add menu to the menu bar

        // Set the menu bar for the frame

        // Create a label to display selected options
        JLabel label = new JLabel("Selected: ");
        add(label, BorderLayout.CENTER);

        // Add action listeners to menu items
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                label.setText("Selected: Open");

        saveItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                label.setText("Selected: Save");

        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

        setSize(300, 200);
        setLocationRelativeTo(null); // Center the window

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new JMenuBarDemo().setVisible(true);



JMenuBar in Java Swing