Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ok, pick a point on the screen of your application. Say, the center. mark that point as the anchor. </p> <p>Now, add a <code>MouseMotionListener</code> to your screen and look for whenever the mouse is moved. You need this point to draw a line. The first point being the anchor.<br> Now, call <code>repaint()</code> every time the mouse moves. </p> <p>In the <code>paintComponent(Graphics g)</code> , use the <code>g.drawLine(anchorX,anchorY,mouseX,mouseY)</code> to draw the line. Since <code>paint()</code> is called before <code>repaint()</code>, you need to give some initial value to these 4 variables. </p> <p><strong>SSCCE:</strong> </p> <pre><code> import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class LineFollower extends JFrame{ int anchorX = 0; int anchorY = 0; int mouseX = 0; int mouseY = 0; JPanel canvas = new JPanel(){ @Override public Dimension getPreferredSize() { return new Dimension(500, 500); } @Override public void paintComponent(Graphics g){ super.paintComponent(); g.setColor(Color.RED); g.drawLine(anchorX, anchorY, mouseX, mouseY); } }; public LineFollower(){ anchorX = 500 / 2; anchorY = 500 / 2; this.getContentPane().add(canvas); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); canvas.addMouseMotionListener(new MouseMotionListener(){ @Override public void mouseDragged(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); repaint(); } @Override public void mouseMoved(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); repaint(); } }); this.pack(); //this.setSize(500,500); this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { new LineFollower(); } }); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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