java - 在 jPanel 上显示鼠标坐标

标签 java swing jpanel mouseevent paint

我想在移动鼠标时使用drawString()方法显示鼠标坐标。这是我当前的代码。这适用于 mouseClicked(MouseEvent e) 方法,但不适用于 mouseMoved(MouseEvent e) 方法。有人可以帮我解决这个问题吗?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    public Test() {
        PaintLocaion paintlocation = new PaintLocaion();
        paintlocation.setSize(400,300);
        add(paintlocation, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }

    private class PaintLocaion extends JPanel {
        int x, y;

        public PaintLocaion() {          
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    x = e.getX();
                    y = e.getY();
                    repaint();
                }
            });
        }      

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.white);
            g.drawString(x + ", " + y, 10, 10);
        }
    }     
}

最佳答案

您需要注册一个MouseMotionListener,而不是注册一个MouseListener...

public PaintLocaion() {          
    addMouseMotionListener(new MouseAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            x = e.getX();
            y = e.getY();
            repaint();
        }
    });
}      

参见How to write a Mouse-Motion Listener了解更多详情

根据 mKorbel 的评论更新

重写paint存在问题,虽然这似乎是合乎逻辑的事情,但由paint方法开始更新的区域在重绘时可能不会更新发生这种情况,您最终可能会遇到一些奇怪的油漆问题。

建议使用paintComponent代替。

如果您尝试在顶部组件上进行绘制,您可以考虑使用玻璃 Pane 或 JXLayer/JLayer

看看Painting in AWT and Swing有关油漆工艺的更多详细信息。 How to use root panes有关玻璃板的详细信息和 How to Decorate Components with the JLayer Class

关于java - 在 jPanel 上显示鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308776/

相关文章:

java - 定制表的通用设计

java - 单击按钮打开静态表单/jFrame

java - 按下 JButton 后多次生成 JPanel "blink"

java - 需要关于如何在面板上方插入小文本短语的想法

java - Hive和JDK-9问题

java - FindBugs 对 ConcurrentHashMap 的调用序列可能不是原子的

java - 更改蓝牙查询扫描时间

java - 在运行时在标签中显示图像

java - 如何根据某些值生成彩色 map

java - JPanel自定义背景