Java – get JPopupMenu size before display
•
Java
I click the right mouse button to display JPopupMenu I want the top right corner of JPopupMenu to be in the click position (not the top left corner by default) To do this, I need to set the X coordinate to mouseevent getX() – popupMenu. getWidth(). The problem is that before the pop-up window is displayed for the first time, its width is equal to 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,200));
SwingUtilities.invokelater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
}
}
Solution
What is the preferred size of JPopupMenu before displaying?
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
