如何在java弹出菜单中显示鼠标XY坐标?
我无法在鼠标指针下的JPOppMenu上显示鼠标的x、y坐标。我在代码中使用JlayerPane的原因是能够像您在CAD应用程序中看到的那样,将笛卡尔坐标系动态添加到JPOppMenu 有人知道它在正确绘制时为什么不显示吗?如何在java弹出菜单中显示鼠标XY坐标?,java,swing,popupmenu,cartesian-coordinates,Java,Swing,Popupmenu,Cartesian Coordinates,我无法在鼠标指针下的JPOppMenu上显示鼠标的x、y坐标。我在代码中使用JlayerPane的原因是能够像您在CAD应用程序中看到的那样,将笛卡尔坐标系动态添加到JPOppMenu 有人知道它在正确绘制时为什么不显示吗? public void show popupwindow(JPanel parentPanel, int xLocation, int yLocation){ Box selectionBox = createSelectionBox(); JPopupM
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);
}
}
不确定,但IIRC
final
和String
彼此有副作用。字符串是不可变的,因此如果您最终生成一个JLabel,我认为您需要在其上创建一个XYMouseLabel
的实例并将其分配给mouseLabel
,但这永远不会添加到任何内容中。您将alsXYMouseLabel
添加到layeredPane
中,但我不知道这是什么,很抱歉,我纠正的是一个打字错误。它应该是一个鼠标贴。请确保将您的代码复制粘贴到新项目中,并确保在将其发布到此处之前它已编译并运行。