我无法在鼠标指针下的 JPopupMenu 上显示鼠标的 x、y 坐标。我在代码中使用 JlayerPane 的原因是能够将笛卡尔坐标系动态添加到 JPopupMenu,就像您在 CAD 应用程序中看到的那样。
有谁知道为什么它在正确绘制时不显示?
public void show popupwindow(JPanel parentPanel, int xLocation, int yLocation){
Box selectionBox = createSelectionBox();
JPopupMenu popupMenu = new JPopupMenu();
// create an instance of my custom mouse cursor label
XYMouseLabel mouseLabel = new XYMouseLabel();
mouseLabel.setBounds(0, 0, selectionBox.getWidth(), selectionBox.getHeight());
JPanel panel = new JPanel();
panel.setSize(new Dimension(500, 400));
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(400, 300));
layeredPane.setBorder(BorderFactory.createTitledBorder("Move the Mouse to get coordinate"));
layeredPane.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
super.mouseMoved(me);
mouseLabel.x = me.getX();
mouseLabel.y = me.getY();
mouseLabel.repaint();
}
});
layeredPane.add(mouseLabel , JLayeredPane.DRAG_LAYER);
layeredPane.add(selectionBox, 2, 0);
panel.add(layeredPane);
popupMenu.add(panel);
popupMenu.show(parentPanel , xLocation,yLocation)
}
public class XYMouseLabel extends JComponent {
public int x;
public int y;
public XYMouseLabel() {
this.setBackground(Color.green);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//hier paint the cartesian coordinate system
String s = x + ", " + y;
g2.setColor(Color.red);
g2.drawString(s, x, y);
}
}