Java 每次鼠标移动时获取鼠标坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21811279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:47:39  来源:igfitidea点击:

Getting mouse coordinates every time mouse moves

javaswingmouselistener

提问by Alpha2k

So i have this code, however i dont get it how to set the mouse coordinates to the label every time the mouse moves ...

所以我有这个代码,但是我不明白如何在每次鼠标移动时将鼠标坐标设置为标签......

timer.schedule(new TimerTask() {

    @Override
    public void run() {
        int mouseX = MouseInfo.getPointerInfo().getLocation().x;
        int mouseY = MouseInfo.getPointerInfo().getLocation().y;
        lblInfo.setText("Nada "+mouseX+mouseY);
    }

}, 1);

Im not even sure if the code is right but what i want it to do is to get the mouse coordinates in the label called lblInfo every time the mouse moves.

我什至不确定代码是否正确,但我想要它做的是在每次鼠标移动时在名为 lblInfo 的标签中获取鼠标坐标。

This code what does is only display it once whenever the program starts...

这段代码的作用是在程序启动时只显示一次......

采纳答案by Salah

You need to implements MouseMotionListener, then add your logic inside mouseMovedmethod like:

您需要implements MouseMotionListener,然后在mouseMoved方法中添加您的逻辑,例如:

public class MyClass implements MouseMotionListener {

    public void mouseMoved(MouseEvent e) {
       System.out.println("X : " + e.getX());
       System.out.println("Y : " + e.getY());
    }

    public void mouseDragged(MouseEvent e) {
       //do something
    }

}

Read more about MouseMotionListener

阅读有关MouseMotionListener 的更多信息

回答by Paul Samsotha

Have a look at this example. You first need to implement mousePressededthenmouseDragged. The first to get the point of the initial press, then the mouseDraggedwill use those coordinates.

看看这个例子。您首先需要实现mousePressededthenmouseDragged。首先获得初始按下的点,然后mouseDragged将使用这些坐标。

addMouseListener(new MouseAdapter() {
     public void mousePressed(MouseEvent me) {
         // Get x,y and store them
         pX = me.getX();
         pY = me.getY();
     }
});
addMouseMotionListener(new MouseAdapter() {
     public void mouseDragged(MouseEvent me) {
         frame.setLocation(frame.getLocation().x + me.getX() - pX, 
              frame.getLocation().y + me.getY() - pY);
     }
});

Complete running example. It uses an undecorate frame and create a JPanelas the header, that you can drag to move the frame.

完整的运行示例。它使用一个未装饰的框架并创建一个JPanel作为标题,您可以拖动它来移动框架。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class UndecoratedExample {
    static JFrame frame = new JFrame();
    static class MainPanel extends JPanel {
        public MainPanel() {
            setBackground(Color.gray);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }
    }

    static class BorderPanel extends JPanel {

        JLabel stackLabel;
        int pX, pY;

        public BorderPanel() {
            ImageIcon icon = new ImageIcon(getClass().getResource(
                    "/resources/stackoverflow1.png"));
            stackLabel = new JLabel();
            stackLabel.setIcon(icon);

            setBackground(Color.black);
            setLayout(new FlowLayout(FlowLayout.RIGHT));

            add(stackLabel);

            stackLabel.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent e) {
                    System.exit(0);
                }
            });
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent me) {
                    // Get x,y and store them
                    pX = me.getX();
                    pY = me.getY();
                }
            });
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent me) {
                    frame.setLocation(frame.getLocation().x + me.getX() - pX, 
                            frame.getLocation().y + me.getY() - pY);
                }
            });
        }
    }

    static class OutsidePanel extends JPanel {

        public OutsidePanel() {
            setLayout(new BorderLayout());
            add(new MainPanel(), BorderLayout.CENTER);
            add(new BorderPanel(), BorderLayout.PAGE_START);
            setBorder(new LineBorder(Color.BLACK, 5));
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                frame.setUndecorated(true);
                frame.add(new OutsidePanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}