我试图在屏幕上出现一个圆圈并跟随鼠标。(最终我将把它变成一个带有光线投射的游戏)我正在使用 MouseMotionListener 并尝试使用 mouseMoved 方法在我的 JPanel 中获取准确的鼠标位置。问题是我将鼠标在屏幕上移动得越远,它变得越不准确。当我的鼠标到达底部时,它正在上方约 20 像素处绘制圆圈。这不是一件落后的事情,因为它永远不会赶上,它总是比它应该在的位置高几个像素。
我尝试使用从 MouseEvents 调用的不同方法,并尝试使用 MousePointerInfo,但没有一个能正常工作。当我将 JFrame 设置为未装饰时,它似乎确实有效,但显然这对于程序看起来并不好,因此我想避免这种情况。
public class Driver {
public static void main(String[] args) {
JFrame frame = new JFrame("Moonlight");
frame.setSize(700, 700);
frame.setLocation(350, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new MoonlightPanel());
frame.setVisible(true);
}
}
public class Panel extends JPanel {
private BufferedImage myImage;
private Graphics myBuffer;
private Timer t;
public Panel () {
myImage = new BufferedImage(700, 700, BufferedImage.TYPE_INT_RGB);
myBuffer = myImage.getGraphics();
t = new Timer(0, new Listener());
t.start();
addMouseMotionListener(new Mouse());
}
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
drawBackground();
/*try {
Point pos = getMousePosition();
myBuffer.setColor(Color.WHITE);
myBuffer.fillOval(pos.x - 10, pos.y - 10, 20, 20);
}
catch(NullPointerException en) {}*/
repaint();
}
}
private class Mouse implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
Point pos = new Point(e.getX(), e.getY());
System.out.println(pos);
myBuffer.setColor(Color.BLUE);
myBuffer.fillOval(pos.x - 10, pos.y - 10, 20, 20);
}
public void mouseDragged(MouseEvent e) {}
}
public void drawBackground() {
setBackground(Color.BLACK);
}
public void paintComponent(Graphics g) {
g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
}
}