如何创建带有菜单的 JButton?

新手上路,请多包涵

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

原文由 Kien Truong 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 482
2 个回答

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

原文由 Steve McLeod 发布,翻译遵循 CC BY-SA 2.5 许可协议

我不明白为什么这比它需要的更难或者为什么你应该使用 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 来放置不同的位置。

原文由 Kenneth Evans 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题