java – 在显示之前获取JPopupMenu大小
作者:互联网
我点击鼠标右键显示JPopupMenu.我希望JPopupMenu的右上角位于点击位置(默认情况下不是左上角).要执行此操作,我需要将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);
}
});
}
}
解决方法:
在显示之前,JPopupMenu的首选大小是多少?
标签:java,swing,preferredsize,jpopupmenu,sizing 来源: https://codeday.me/bug/20190728/1565207.html