Note that there are some explanatory texts on larger screens.

plurals
  1. POMake circle and then move circle on mouse dragged event
    primarykey
    data
    text
    <p>How to draw circle on mouse dragged event, and then how to move that circle on mouse dragged event in Java?</p> <p>My code is below.</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; class r extends JPanel { public int x1, x2, y1, y2, r, w, h,xDist,yDist; public static boolean flag = false, pressFlag = false; public r() { setBackground(Color.WHITE); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent m) { // pressFlag = true; if (r &gt; (int) Math.sqrt(Math.abs(m.getX() - x1) * Math.abs(m.getX() - x1) + Math.abs(m.getY() - y1) * Math.abs(m.getY() - y1))) { flag = true; yDist=xDist=x2 = y2 = 0; } else { x1 = y1 = 0; r=x2 = y2 = 0; x1 = m.getX(); y1 = m.getY(); } repaint(); } public void mouseReleased(MouseEvent m) { w = x2 - x1; h = y2 - y1; r = (int) Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); flag = false; } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent m) { if (flag &amp;&amp; (x2!=0 &amp;&amp; y2!=0)) { xDist=(m.getX()-x2); yDist=(m.getY()-y2); } x2 = m.getX(); y2 = m.getY(); repaint(); } }); } public void paintComponent(Graphics g) { super.paintComponent(g); if (flag) { x1=x1+xDist; y1=y1+yDist; g.drawOval(x1, y1, w, h); } else { g.drawOval(x1, y1, x2 - x1, y2 - y1); } } } public class q extends JFrame { public static void main(String[] args) { JFrame jFrame = new JFrame(); jFrame.setSize(300, 300); jFrame.add(new r()); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } </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.
 

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