我试图解决这个问题,当我终于找到它背后的原因时 - 调用静态方法 get_mouse_x() 和 get_mouse_y() 根据调用位置返回不同的结果:如果它是从对象的 update() 方法调用的,它总是返回 0.0,而如果它从 draw() 方法调用,它返回有效的答案。
按钮类(出现问题的地方):
public abstract class Button extends Drawable_object {
...
@Override
public void update()
{
super.update();
mouseOver_last = mouseOver;
mx = Game_logic.get_mouse_x();
my = Game_logic.get_mouse_y();
// for some reasons mx and my are always 0.0
if ((mx <= x + ((double)width / 2))&&
(mx >= x - ((double)width / 2))&&
(my >= y - ((double)height / 2))&&
(my <= y + ((double)height / 2)))
{ mouseOver = true;}
else mouseOver = false;
...
}
@Override
public void draw(Graphics g)
{
super.draw (g);
g.drawString ("x - width / 2 = " + String.valueOf(x - width), 10, 30);
g.drawString ("mouse_x = " + String.valueOf(Game_logic.get_mouse_x()), 10, 40);
// at this point get_mouse_x() returns true result
g.drawString ("x + width / 2 = " + String.valueOf(x + width), 10, 50);
g.drawString ("y - width / 2 = " + String.valueOf(y - width), 200, 30);
g.drawString ("mouse_y= " + String.valueOf(Game_logic.get_mouse_y()), 200, 40);
// at this point get_mouse_y() returns true result
g.drawString ("y + width / 2 = " + String.valueOf(y + width), 200, 50);
g.drawString ("mouseOver = " + String.valueOf(mouseOver), 10, 80);
...
}
...
}
鼠标坐标在 Board 类中使用 MouseAdapter 设置:
public class Board extends JPanel implements ActionListener {
...
private class MAdapter2 extends MouseAdapter {
@Override
public void mouseMoved(MouseEvent e) {
Game_logic.set_mouse_x(e.getX());
Game_logic.set_mouse_y(e.getY());
}
}
...
}
所有的东西都在同一个 Board 类中更新和绘制:
public void actionPerformed(ActionEvent e) {
update(); // calls update() method in every object
checkCollisions(); //checks collision
repaint(); // calls draw() method in every drawable object
}
那么为什么在对象的 update() 方法中调用 Game_logic.get_mouse_x() 和 Game_logic.get_mouse_y() 会返回 0.0 的值,而在对象的 draw() 方法中调用它们总是返回正确的值呢?