我想在移动鼠标时使用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);
}
}
}
答案 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)
您可以尝试使用MouseMotionListener
http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html