我想在移动鼠标时使用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/