search
HomeJavajavaTutorialHow to use Java GUI programming menu components

How to use Java GUI programming menu components

Common menu-related components are given in the following table:

Menu component name Function
MenuBar Menu bar, container of menu.
Menu Menu component, container of menu items. It is also a subclass of Menultem, so it can be used as a menu item
PopupMenu Context menu component (right-click menu component)
Menultem Menu item component.
CheckboxMenuItem Checkbox menu item component

The following figure is a common menu-related component integration system diagram :

How to use Java GUI programming menu components

Use of menu related components:

1. Prepare menu item components, these components can be MenuItem and its subclass objects

2. Prepare the menu component Menu or PopupMenu (right-click to pop up the submenu), and add the menu item component prepared in the first step;

3. Prepare the menu bar component MenuBar, and add the menu item component prepared in the second step. The good menu component Menu is added;

4. Add the menu bar component prepared in the third step to the window object for display.

Tips:

1. If you want to add a dividing line between menu items in a menu, you only need to call Menu's add (new MenuItem(-)).

2. If you want to associate a shortcut key function with a menu item, you only need to set it when creating the menu item object. For example, to associate the ctrl shift / shortcut key with a menu item, you only need: new MenuItem( "Menu item name", new MenuShortcut(KeyEvent.VK_Q,true);

Case 1:

Use common menu components in awt to complete the effect below

How to use Java GUI programming menu components

Demo code 1:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleMenu {
    //创建窗口
    private Frame frame = new Frame("这里测试菜单相关组件");
    //创建菜单条组件
    private MenuBar menuBar = new MenuBar();
    //创建文件菜单组件
    private Menu fileMenu = new Menu("文件");
    //创建编辑菜单组件
    private Menu editMenu = new Menu("编辑");
    //创建新建菜单项
    private MenuItem newItem = new MenuItem("新建");
    //创建保存菜单项
    private MenuItem saveItem = new MenuItem("保存");
    //创建退出菜单项
    private MenuItem exitItem = new MenuItem("退出");
    //创建自动换行选择框菜单项
    private CheckboxMenuItem autoWrap = new CheckboxMenuItem("自动换行");
    //创建复制菜单项
    private MenuItem copyItem = new MenuItem("复制");
    //创建粘贴菜单项
    private MenuItem pasteItem = new MenuItem("粘贴");
    //创建格式菜单
    private Menu formatMenu = new Menu("格式");
    //创建注释菜单项
    private MenuItem commentItem = new MenuItem("注释");
    //创建取消注释菜单项
    private MenuItem cancelItem = new MenuItem("取消注释");
    //创建一个文本域
    private TextArea ta = new TextArea(6, 40);
    public void init(){
        //定义菜单事件监听器
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                ta.append("单击“"+command+"”菜单\n");
                if (command.equals("退出")){
                    System.exit(0);
                }
            }
        };
        //为注释菜单项和退出菜单项注册监听器
        commentItem.addActionListener(listener);
        exitItem.addActionListener(listener);
        //为文件菜单fileMenu添加菜单项
        fileMenu.add(newItem);
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);
        //为编辑菜单editMenu添加菜单项
        editMenu.add(autoWrap);
        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        //为格式化菜单formatMenu添加菜单项
        formatMenu.add(commentItem);
        formatMenu.add(cancelItem);
        //将格式化菜单添加到编辑菜单中,作为二级菜单
        editMenu.add(new MenuItem("-"));
        editMenu.add(formatMenu);
        //将文件菜单和编辑菜单添加到菜单条中
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        //把菜单条设置到frame窗口上
        frame.setMenuBar(menuBar);
        //把文本域添加到frame中
        frame.add(ta);
        //设置frame最佳大小并可见
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new SimpleMenu().init();
    }
}

Case 2:

Achieve the following effect through PopupMenu:

How to use Java GUI programming menu components

Achieved Ideas:

1. Create the PopubMenu menu component;

2. Create multiple MenuItem menu items and add them to the PopupMenu;

3. Add the PopupMenu to the target component Medium;

For components that need to display the PopubMenu menu, register a mouse listener event. When the user releases the right button, the menu pops up.

Demo code 2:

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class PopupMenuTest {
    private Frame frame = new Frame("这里测试PopupMenu");
    // 创建PopubMenu菜单
    private PopupMenu popupMenu = new PopupMenu();
    // 创建菜单条
    private MenuItem commentItem = new MenuItem("注释");
    private MenuItem cancelItem = new MenuItem("取消注释");
    private MenuItem copyItem = new MenuItem("复制");
    private MenuItem pasteItem = new MenuItem("保存");
    // 创建一个文本域
    private TextArea ta = new TextArea("我爱中华!!!", 6, 40);
    // 创建一个Panel
    private Panel panel = new Panel();
    public void init() {
        // 把菜单项添加到PopupMenu中
        popupMenu.add(commentItem);
        popupMenu.add(cancelItem);
        popupMenu.add(copyItem);
        popupMenu.add(pasteItem);
        // 设置panel大小
        panel.setPreferredSize(new Dimension(300, 100));
        // 把PopupMenu添加到panel中
        panel.add(popupMenu);
        // 为panel注册鼠标事件
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                boolean flag = e.isPopupTrigger();
                // 判断当前鼠标操作是不是触发PopupMenu的操作
                if (flag) {
                    // 让PopupMenu显示在panel上,并且跟随鼠标事件发生的地方显示
                    popupMenu.show(panel, e.getX(), e.getY());
                }
            }
        });
        // 把ta添加到frame中间区域中
        frame.add(ta);
        // 把panel添加到frame底部
        frame.add(panel, BorderLayout.SOUTH);
        // 设置frame最佳大小,并可视;
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new PopupMenuTest().init();
    }
}

The above is the detailed content of How to use Java GUI programming menu components. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor