Getting mouse coordinates method returning different values depending on time called

98 views Asked by At

I was trying to solve this problem, when I finally found out the reason behind it - calling static methods get_mouse_x() and get_mouse_y() return different results depending on where it was called: if its called from object`s update() method, it always return 0.0, while if its called from draw() method, it returns valid answer.

Button class (where problems occurs):

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);
    ...
    }

...
}

The mouse coordinates are set in Board class using 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());
    }

}

...

}

All the things are updated and drawn in same Board class:

public void actionPerformed(ActionEvent e) {

update(); // calls update() method in every object
checkCollisions(); //checks collision
repaint(); // calls draw() method in every drawable object

}

So why does calling Game_logic.get_mouse_x() and Game_logic.get_mouse_y() inside object`s update() method return 0.0 values, and calling them inside objects draw() method always return correct values?

0

There are 0 answers