在显示之前获取JPopupMenu大小

时间:2013-10-21 09:46:45

标签: java swing jpopupmenu preferredsize sizing

我右键单击显示JPopupMenu。我希望JPopupMenu'右上角位于click location(不是左上角,默认情况下)。要执行此操作,我需要将X坐标设置为mouseEvent.getX() - popupMenu.getWidth()。问题是,在第一次显示弹出窗口之前,其宽度等于0.

SSCCE:

public class PopupTest2 {
    public static void main(String[] a) {
        final JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createLineBorder(Color.RED));

        final JPopupMenu menu = new JPopupMenu();

        for (int i = 0; i < 10; i++) {
            JMenuItem item = new JMenuItem("Item #"+String.valueOf(i));
            menu.add(item);
        }

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    // first time works wrong
                    menu.show(panel, e.getX() - menu.getWidth(), e.getY());
                }
            }
        });
        frame.setContentPane(panel);
        frame.setUndecorated(true);
        frame.setBackground(new Color(50, 50, 50, 200));

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }
}

4 个答案:

答案 0 :(得分:4)

使用preferredSize(如前所述)是获取位置的方法。

但是(正在进行搜索:-):手动显示弹出窗口不是推荐的方法。一个非常干净的实现将使用componentPopupMenu属性并根据需要实现getPopupLocation,如

JPanel panel = new JPanel(new BorderLayout()) {

    @Override
    public Point getPopupLocation(MouseEvent event) {
        JPopupMenu menu = getComponentPopupMenu();
        if (menu == null || event == null) return null;
        return new Point(event.getX() - menu.getPreferredSize().width, event.getY());
    }

};
JPopupMenu menu = new JPopupMenu();
panel.setComponentPopupMenu(menu);

答案 1 :(得分:2)

显示之前JPopupMenu的首选尺寸是什么?

答案 2 :(得分:1)

您可以将上下文菜单的宽度确定为ist元素的最高首选宽度吗?

答案 3 :(得分:0)

使用popup.getPreferredSize().widthpopup.getPreferredSize().height,您可以在显示之前获得弹出窗口大小。

这是一个将弹出菜单放在按钮顶部的示例:

but_menu = new JButton("");
but_menu.addMouseListener(new MouseAdapter() {
   public void mousePressed(MouseEvent e) {
      Point p = but_menu.getLocation();
      Point dest = new Point();
      dest.x = 0 - popup.getPreferredSize().width + but_menu.getWidth();
      dest.y = 0 - popup.getPreferredSize().height;
      popup.show(but_menu,dest.x,dest.y);
   }
});