在jPanel上显示鼠标坐标

时间:2013-08-19 07:47:36

标签: 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);
        }
    }     
}

2 个答案:

答案 0 :(得分:4)

您需要注册MouseListener ...

,而不是注册MouseMotionListener
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

如果您尝试在顶部组件上绘画,可以考虑使用玻璃窗格或JXLayer / JLayer

请查看Painting in AWT and Swing以了解有关绘画过程的更多详细信息。有关玻璃窗格和How to use root panes

的详细信息,请How to Decorate Components with the JLayer Class

答案 1 :(得分:2)