Home Java javaTutorial How to use Java GUI programming menu components

How to use Java GUI programming menu components

May 28, 2023 am 08:16 AM
java gui

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();
    }
}
Copy after login

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();
    }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles