如何创建带有菜单的 JButton?

发布于 2024-08-09 20:37:41 字数 107 浏览 7 评论 0 原文

我想在我的应用程序中创建一个工具栏。如果单击该工具栏上的按钮,它将弹出一个菜单,就像 Eclipse 的工具栏中一样。我不知道如何在 Swing 中执行此操作。有人可以帮我吗?我尝试过谷歌但一无所获。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

蒗幽 2024-08-16 20:37:41

这在 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);
    }
}

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.

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);
    }
}
萌辣 2024-08-16 20:37:41

我不明白为什么这比需要的更难,也不明白为什么你应该使用 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);
    }
});

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

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.

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().

隐诗 2024-08-16 20:37:41

这是一个简单而漂亮的类

在此处输入图像描述

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) {}
        });
    }
}

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) {}
        });
    }
}
时光病人 2024-08-16 20:37:41

我认为这与 AWT 中的相同。

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

I think it's the same as in AWT.

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

青春如此纠结 2024-08-16 20:37:41

请参阅 如何使用菜单

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

白馒头 2024-08-16 20:37:41

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

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

Java 教程:如何使用操作

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

Java Tutorials: How to Use Tool Bars and this

Java Tutorials: How to Use Actions

孤云独去闲 2024-08-16 20:37:41

亚当·古德在上面问道:

您的解决方案是否具有以下行为:如果您在菜单打开的情况下再次单击按钮,它会再次弹出菜单,而不是关闭菜单?

事实证明这是一项测试任务。我最终用 invokeLater 解决了这个问题,以在特定情况下重新消失弹出窗口。我的解决方案还允许客户定制按钮和弹出菜单。

    /**
 * A button that will popup a menu.
 * The button itself is a JLabel and can be adjusted with all
 * label attributes. The popup menu is returned by getPopup;
 * menu items must be added to it.
 * <p>
 * Clicks outside the menu will dismiss it.
*/
public class MenuButton extends JLabel 
        implements MouseListener, PopupMenuListener {
    JPopupMenu popMenu;

    @SuppressWarnings("")
    public MenuButton() {
        super();
        popMenu = new JPopupMenu();
        addMouseListener(this);
        popMenu.addPopupMenuListener(this);
    }

    public JPopupMenu getPopup() { return popMenu; }
    
    @Override
    public void mousePressed(MouseEvent e) {
        if ( ! popMenu.isShowing()) {
            popMenu.show(this, 0, getBounds().height);
        }
    }
    @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 
        SwingUtilities.invokeLater(()->{
            if (popMenu.isShowing()) {
                //  if shpwing, it was hidden and reshown
                //  by a mouse down in the 'this' button
                popMenu.setVisible(false);
            }
        });
    }

    @Override public void mouseClicked(MouseEvent e) { }
    @Override public void mouseReleased(MouseEvent e) { }
    @Override public void mouseEntered(MouseEvent e) { }
    @Override public void mouseExited(MouseEvent e) { }
    @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { }
    @Override public void popupMenuCanceled(PopupMenuEvent e) { }

} // end MenuButton

调用示例

    MenuButton button = new MenuButton();
    JPopupMenu menu = button.getPopup();
    menu.add("Browse Sample");
    menu.add("Save As ...");
    Icon hamburger = IOUtils.loadIconResource(
            IndexGofer.class, "images/hamburgerMenu.png");
            (IOUtils is on page http://physpics.com/Java/tools/
                  You should use your own tool to load an icon.)
    button.setIcon(hamburger);
    button.setOpaque(false);

Above, Adam Goode asked,

Does your solution have the behavior where if you click the button again with the menu up, it pops up the menu again, instead of dismissing it?

This turned out to be a testing task. I finally solved it with an invokeLater to re-vanish the popup in that particular case. My solution also allows the client to tailor the button and the popup menu.

    /**
 * A button that will popup a menu.
 * The button itself is a JLabel and can be adjusted with all
 * label attributes. The popup menu is returned by getPopup;
 * menu items must be added to it.
 * <p>
 * Clicks outside the menu will dismiss it.
*/
public class MenuButton extends JLabel 
        implements MouseListener, PopupMenuListener {
    JPopupMenu popMenu;

    @SuppressWarnings("")
    public MenuButton() {
        super();
        popMenu = new JPopupMenu();
        addMouseListener(this);
        popMenu.addPopupMenuListener(this);
    }

    public JPopupMenu getPopup() { return popMenu; }
    
    @Override
    public void mousePressed(MouseEvent e) {
        if ( ! popMenu.isShowing()) {
            popMenu.show(this, 0, getBounds().height);
        }
    }
    @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 
        SwingUtilities.invokeLater(()->{
            if (popMenu.isShowing()) {
                //  if shpwing, it was hidden and reshown
                //  by a mouse down in the 'this' button
                popMenu.setVisible(false);
            }
        });
    }

    @Override public void mouseClicked(MouseEvent e) { }
    @Override public void mouseReleased(MouseEvent e) { }
    @Override public void mouseEntered(MouseEvent e) { }
    @Override public void mouseExited(MouseEvent e) { }
    @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { }
    @Override public void popupMenuCanceled(PopupMenuEvent e) { }

} // end MenuButton

Sample invocation

    MenuButton button = new MenuButton();
    JPopupMenu menu = button.getPopup();
    menu.add("Browse Sample");
    menu.add("Save As ...");
    Icon hamburger = IOUtils.loadIconResource(
            IndexGofer.class, "images/hamburgerMenu.png");
            (IOUtils is on page http://physpics.com/Java/tools/
                  You should use your own tool to load an icon.)
    button.setIcon(hamburger);
    button.setOpaque(false);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文