Note that there are some explanatory texts on larger screens.

plurals
  1. POCursor disappears while calling repaint in mouseMoved?
    text
    copied!<p>I have a problem with drawing horizontal and vertical lines from the cursor position while the cursor is moving. The cursor seem to disappear.</p> <p>I've attached a MouseInputAdapter to my swing component, which has a mouseMoved method which call repaint();</p> <p>Calling repaint will cause a paintComponent(Graphics g) to be called. In paintComponent i paint the horizontal and vertical line:</p> <pre><code>Dimension dim = getSize(); g2.setColor(Color.white); g2.fillRect(0, 0, dim.width, dim.height); g2.setColor(Color.black); Point pos = this.getMousePosition(); g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y)); g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight())); </code></pre> <p>Here is a screenshot:</p> <p><img src="https://i.stack.imgur.com/VCbSj.jpg" alt="enter image description here"></p> <p>The cursor should be in the white area that exists between the big horizontal line and the vertical one and should be at the left of the big number 1.2434307...</p> <p>When i move the cursor with my mouse i can see the cursor (crosshair) flickering which makes me believe my paint method is painting over the cursor.</p> <p>Anyone know where the problem may lie?</p> <p>As requested i've added a little test code.</p> <pre><code>public class TestApp extends JFrame { public TestApp() { super("TestApp"); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(new CustomComponent(), BorderLayout.CENTER); this.setSize(300, 300); this.setVisible(true); } class CustomComponent extends JComponent { public CustomComponent() { setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); MouseInputAdapter mia = new MouseInputAdapter() { @Override public void mouseMoved(MouseEvent e) { repaint(); } }; addMouseMotionListener(mia); addMouseListener(mia); } @Override public void paintComponent(Graphics g) { Dimension dim = getSize(); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.white); g2.fillRect(0, 0, dim.width, dim.height); g2.setColor(Color.black); Point pos = this.getMousePosition(); if (pos != null) { g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y)); g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight())); g2.drawString("where is my cursor?", pos.x, pos.y); } } } public static void main(String[] args) { new TestApp(); } } </code></pre>
 

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