Java 如何使用菜单创建 JButton?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1692677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:37:37  来源:igfitidea点击:

How to create a JButton with a menu?

javaswingmenujbuttonjpopupmenu

提问by Kien Truong

I want to create a Toolbar in my application. If you click a button on that toolbar, it will pop up a menu, just like in Eclipse's toolbar. I don't know how to do this in Swing. Can someone help me please? I've tried Google but found nothing.

我想在我的应用程序中创建一个工具栏。如果单击该工具栏上的按钮,它将弹出一个菜单,就像在 Eclipse 的工具栏中一样。我不知道如何在 Swing 中做到这一点。有人能帮助我吗?我试过谷歌,但一无所获。

采纳答案by Steve McLeod

This is way harder in Swing than it needs to be. So instead of pointing you to tutorials I've created a fully working example.

这在 Swing 中比它需要的要困难得多。因此,我没有将您指向教程,而是创建了一个完整的示例。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ToolbarDemo {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(600, 400));
        final JToolBar toolBar = new JToolBar();

        //Create the popup menu.
        final JPopupMenu popup = new JPopupMenu();
        popup.add(new JMenuItem(new AbstractAction("Option 1") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Option 1 selected");
            }
        }));
        popup.add(new JMenuItem(new AbstractAction("Option 2") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Option 2 selected");
            }
        }));

        final JButton button = new JButton("Options");
        button.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });
        toolBar.add(button);

        frame.getContentPane().add(toolBar, BorderLayout.NORTH);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

回答by Cristina

I think it's the same as in AWT.

我认为这与 AWT 中的相同。

You should put an ActionCommand on that button and when it's executed show the pop-up menu according to the mouse coordinates.

您应该在该按钮上放置一个 ActionCommand,并在它执行时根据鼠标坐标显示弹出菜单。

回答by jitter

I'm not sure I understand you correctly but if you want to know how to make toolbars in Swing check this

我不确定我是否正确理解你,但如果你想知道如何在 Swing 中制作工具栏,请检查这个

Java Tutorials: How to Use Tool Barsand this

Java 教程:如何使用工具栏和这个

Java Tutorials: How to Use Actions

Java 教程:如何使用操作

回答by TH.

See the section Bringing Up a Popup Menu, in How to Use Menus.

请参见造就了弹出菜单,在如何使用菜单

回答by Kenneth Evans

I don't see why this is harder than it needs to be or why you should use a MouseListener. The solution by Steve McLeod works, but where the menu appears depends on where the mouse was clicked. Why not just use an ActionListener as normally used for a JButton. It seems neither harder nor less hard.

我不明白为什么这比它需要的更难,或者为什么你应该使用 MouseListener。Steve McLeod 的解决方案有效,但菜单出现的位置取决于单击鼠标的位置。为什么不像通常用于 JButton 那样使用 ActionListener。看起来既不难也不难。

final JPopupMenu menu = new JPopupMenu();
menu.add(...whatever...);

final JButton button = new JButton();
button.setText("My Menu");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev) {
        menu.show(button, button.getBounds().x, button.getBounds().y
           + button.getBounds().height);
    }
});

This positions the menu about the same as a menu in a JMenuBar for me, and the position is consistent. You could place it differently by modifying the x and y in menu.show().

这对我来说,菜单的位置与 JMenuBar 中的菜单大致相同,并且位置是一致的。您可以通过修改 menu.show() 中的 x 和 y 以不同方式放置它。

回答by luca

Here is a simple and nice class

这是一个简单而漂亮的类

enter image description here

在此处输入图片说明

import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MenuButton extends JToggleButton {

    JPopupMenu popup;

    public MenuButton(String name, JPopupMenu menu) {
        super(name);
        this.popup = menu;
        addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ev) {
                JToggleButton b = MenuButton.this;
                if (b.isSelected()) {
                    popup.show(b, 0, b.getBounds().height);
                } else {
                    popup.setVisible(false);
                }
            }
        });
        popup.addPopupMenuListener(new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                MenuButton.this.setSelected(false);
            }
            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {}
        });
    }
}