jmenu

‮figi.www‬tidea.com

The JMenu class in Java is used to create a menu bar in a GUI application. It is a subclass of the AbstractButton class, and like all the other components in the Swing package, it is implemented using the model-view-controller (MVC) architecture.

A JMenu can contain menu items (JMenuItem), other menus (JMenu), or separators (JSeparator). It can also be nested inside another JMenu.

Here's an example of how to create a JMenu in Java:

import javax.swing.*;

public class MyMenu extends JFrame {
    public MyMenu() {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenu editMenu = new JMenu("Edit");

        JMenuItem newItem = new JMenuItem("New");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem cutItem = new JMenuItem("Cut");
        JMenuItem copyItem = new JMenuItem("Copy");
        JMenuItem pasteItem = new JMenuItem("Paste");

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        editMenu.add(cutItem);
        editMenu.add(copyItem);
        editMenu.add(pasteItem);

        menuBar.add(fileMenu);
        menuBar.add(editMenu);

        setJMenuBar(menuBar);

        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MyMenu();
    }
}

In this example, we first create a JMenuBar object and two JMenu objects for the "File" and "Edit" menus. Then we create six JMenuItem objects for the "New", "Open", "Save", "Cut", "Copy", and "Paste" menu items. We add the menu items to their respective menus using the add() method, and add the menus to the menu bar using the add() method as well. Finally, we set the menu bar using the setJMenuBar() method and display the window.