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