マウスを動かしたときに 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);
}
}
}