如何用菜单创建JButton?

Kie*_*ong 32 java swing menu jbutton jpopupmenu

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

Ste*_*eod 31

这在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我也做了一些不同的事情:popup.show(c,0,c.getHeight()); (2认同)

Ken*_*ans 14

我不明白为什么这比它需要的更难或为什么你应该使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

  • 该方法的问题在于,弹出菜单仅在用户释放鼠标按钮时出现。菜单应该在鼠标按下时出现,而不是在鼠标松开时出现 (2认同)