【发布时间】:2019-09-28 22:47:06
【问题描述】:
我试图在屏幕上显示一个圆圈并跟随鼠标移动。 (最终我将把它变成一个带有光线投射的游戏)我正在使用 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);
}
}
【问题讨论】:
-
我认为您发布的代码有误。
public class Panel extends JPanel。不应该是public class MoonlightPanel extends JPanel吗? -
你的期望和现实不匹配,你移动鼠标的速度越快,你得到的事件越少,点的距离就越远。更好的解决方案可能是跟踪列表中的所有点,并在每个点之间按顺序画一条线
标签: java mouselistener mousemotionlistener