我在鼠标右键单击时显示了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);
}
});
}
}
使用 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);
显示之前JPopupMenu
的首选大小是多少?
也许您可以将上下文菜单的宽度确定为 ist 元素的最高首选宽度?
使用popup.getPreferredSize().width
和popup.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);
}
});