java - 使 JPopupMenu 以一定的左下角坐标显示

标签 java swing jpopupmenu

假设我想用 Java 制作一个按钮,这样当你点击它时,一个 JPopupMenu出现。它出现的相关代码是 menu.show(button, button.getWidth()/2, button.getHeight()/2);,这使得 JPopupMenu 的左上角显示在按钮的中心,如下图:

Current Swing JPopupMenu

但是,我希望它的左下角位于按钮的中心,有点像 iTunes 所做的(左下角下方有一个按钮,其大小与 + 按钮在它的左边):

enter image description here

我试图通过获取 JPopupMenu 的高度并将其添加到显示弹出菜单的 y 坐标来实现这一点,但我发现 JPopupMenu 在可见之前的高度为 0,这对我没有帮助,因为我试图告诉计算机在哪里可以看到它。此外,不可能在偏移量中进行硬编码,因为弹出窗口中的项目数不一定相同。

如何才能显示我的高度未知的 JPopupMenu,使其左下角坐标与给定坐标相匹配?

最佳答案

基本上,这会创建一个弹出菜单并使用 JComponent#setComponentPopupMenu 将其注册到组件中.这意味着我不再需要监视鼠标事件或决定何时显示弹出窗口。

然后我覆盖 JComponent#getPopupLocation并计算我希望弹出窗口出现的位置。

基本上,我得到了 JComponent#getComponentPopupMenu , 获取它的首选大小并计算适当的偏移量,以便左下角现在出现在组件的中心...

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestPopup02 {

    public static void main(String[] args) {
        new TestPopup02();
    }

    public TestPopup02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            JPopupMenu menu = new JPopupMenu();
            menu.add(new JMenuItem("Edit Playlist"));
            menu.addSeparator();
            menu.add(new JMenuItem("Check for Available Downloads..."));
            menu.addSeparator();
            menu.add(new JMenuItem("Export..."));
            menu.add(new JMenuItem("Burn Playlist to Disc"));
            menu.add(new JMenuItem("Copy To Play Order"));
            menu.addSeparator();
            menu.add(new JMenuItem("Delete"));
            setComponentPopupMenu(menu);
        }

        @Override
        public Point getPopupLocation(MouseEvent event) {
            // Get the registered popup menu...
            JPopupMenu popup = getComponentPopupMenu();
            // Get the super point, just in case...
            Point pos = super.getPopupLocation(event);
            if (popup != null) {
                // Create a new "point" location
                pos = new Point();
                // get the preferred size of the menu...
                Dimension size = popup.getPreferredSize();
                // Adjust the x position so that the left side of the popup
                // appears at the center of  the component
                pos.x = (getWidth() / 2);
                // Adjust the y position so that the y postion (top corner)
                // is positioned so that the bottom of the popup
                // appears in the center
                pos.y = (getHeight() / 2) - size.height;
            }
            return pos;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Simply draws a cross in the center of the window, so you 
            // know where the center is...
            int width = getWidth() - 1;
            int height = getHeight() - 1;
            g.drawLine(width / 2, 0, width / 2, height);
            g.drawLine(0, height / 2, width, height / 2);
        }

    }
}

使用 Mac 输出更新

enter image description here

按钮示例

您不太可能找到完全满足您需求的解决方案。任何开发人员都可以培养的最伟大的技能之一就是能够根据需要采纳想法并加以塑造。

前面的示例包含您需要的一切,您只需要能够实现从概念到解决方案的飞跃。

getPopupLocation 是组件弹出 API 的一部分,因此覆盖该方法或调用它可能不是您所需要的(除非您有一个用于该任务的专用按钮,这可能不是一件坏事),因此您需要根据您的需要调整解决方案...

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestPopup02 {

    public static void main(String[] args) {
        new TestPopup02();
    }

    public TestPopup02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JButton button;
        private JPopupMenu popup;

        public TestPane() {
            popup = new JPopupMenu();
            popup.add(new JMenuItem("Edit Playlist"));
            popup.addSeparator();
            popup.add(new JMenuItem("Check for Available Downloads..."));
            popup.addSeparator();
            popup.add(new JMenuItem("Export..."));
            popup.add(new JMenuItem("Burn Playlist to Disc"));
            popup.add(new JMenuItem("Copy To Play Order"));
            popup.addSeparator();
            popup.add(new JMenuItem("Delete"));

            setLayout(new GridBagLayout());
            button = new JButton("+");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    popup.pack();
                    Point pos = new Point();
                    // get the preferred size of the menu...
                    Dimension size = popup.getPreferredSize();
                    // Adjust the x position so that the left side of the popup
                    // appears at the center of  the component
                    pos.x = (button.getWidth() / 2);
                    // Adjust the y position so that the y postion (top corner)
                    // is positioned so that the bottom of the popup
                    // appears in the center
                    pos.y = (button.getHeight() / 2) - size.height;
                    popup.show(button, pos.x, pos.y);
                }
            });
            add(button);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Simply draws a cross in the center of the window, so you 
            // know where the center is...
            int width = getWidth() - 1;
            int height = getHeight() - 1;
            g.drawLine(width / 2, 0, width / 2, height);
            g.drawLine(0, height / 2, width, height / 2);
        }
    }
}

关于java - 使 JPopupMenu 以一定的左下角坐标显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16475417/

相关文章:

java - 如何为可选流中的列表映射索引 0 处的值

java - 为什么 "\t"在 Java String.split 中有效,但在 "\."中无效?

java - 使用 Java 8 流映射函数来执行长时间运行的任务

java - 仅在单击鼠标 Swing 时打开 popupMenu

java - libGdx 多边形碰撞检测

java - 如何通过 Main - NullpointerException 错误更改进度条的值

java - JEdi​​torPane 不尊重 html 表格高度 100%

java - 当我的体重秤关闭时,我的 JFrame 卡住

java - 右键单击时不显示 JPopupMenu

java - 将静态文本添加到 Java Swing 菜单的最佳方法是什么?