首页 > 解决方案 > 当鼠标与 Graphics2D 一起移动时,如何显示 X 和 Y 鼠标位置?

问题描述

当鼠标与 Graphics2D 一起移动时,如何显示 X 和 Y 鼠标位置?

我正在尝试在鼠标移动时显示坐标,但我可以使用System.out.println,我想使用drawString.join("", 10, 5)

那我怎么能达到呢?

*这就是我所做的

public class Bell2 extends JPanel {
    static JFrame frame=new JFrame();


    public Bell() {

    }

     public void paint(Graphics g){
            Graphics2D g2=(Graphics2D)g;
            g2.setColor(Color.yellow);
            //Here's where I struggle
            g2.drawString.join ("mouseX, mouseY, C");


     }
    public static void main(String[] args) {

        frame.setSize(500,300);
        frame.setLocation(300,200);
        frame.setVisible(true);
        frame.setBackground(Color.black);

         Robot robot = null;
            try {
                robot = new Robot();
            } catch (AWTException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              Color c = robot.getPixelColor(456,141);


        double mouseY=1.0;
        double mouseX=1.0;
        while(mouseX !=0 || mouseY  !=0) {

            mouseX = MouseInfo.getPointerInfo().getLocation().getX();
             mouseY = MouseInfo.getPointerInfo().getLocation().getY();

             System.out.println("x: "+mouseX+" y: "+mouseY+" c: "+c);

        }

    }

}

标签: javaswinggraphics2dawtrobot

解决方案


不确定这是否正是您要查找的内容,但是,如果您想与原始示例保持相当接近,您可以考虑做这样的事情:

    public static void main(String[] args) {
        frame.setSize(500,300);
        frame.setLocation(300,200);
        frame.setVisible(true);
        frame.setBackground(Color.black);

        try {
            final Robot robot = new Robot();
            handleMouse(robot);
        } catch (final AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void handleMouse(final Robot robot) {
        int mouseX = 1;
        int mouseY = 1;
        while (mouseX !=0 || mouseY !=0) {
            final Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
            mouseX = mouseLocation.x;
            mouseY = mouseLocation.y;
            final Color currentColor = robot.getPixelColor(mouseX, mouseY);
            System.out.println(String.format("x: %d, y: %d, c: %s", mouseX, mouseY, currentColor));
        }
    }

请注意,每次都会currentColor更新;在您的原始代码段中并非如此。mouseXmouseY

如果您正在查看终端上的输出,需要注意的另一件事 - 颜色只会在保持 <= 255;时才会mouseX发生变化;mouseY超出该值,您可能只会看到以下输出:

java.awt.Color[r=255,g=255,b=255]

推荐阅读