Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting mouse coordinates method returning different values depending on time called
    text
    copied!<p>I was trying to solve <a href="https://stackoverflow.com/questions/20435152/issue-comparing-doubles">this</a> 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.</p> <p>Button class (where problems occurs):</p> <pre><code>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 &lt;= x + ((double)width / 2))&amp;&amp; (mx &gt;= x - ((double)width / 2))&amp;&amp; (my &gt;= y - ((double)height / 2))&amp;&amp; (my &lt;= 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); ... } ... } </code></pre> <p>The mouse coordinates are set in Board class using MouseAdapter:</p> <pre><code>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()); } } ... } </code></pre> <p>All the things are updated and drawn in same Board class:</p> <pre><code>public void actionPerformed(ActionEvent e) { update(); // calls update() method in every object checkCollisions(); //checks collision repaint(); // calls draw() method in every drawable object } </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload