Note that there are some explanatory texts on larger screens.

plurals
  1. PODraw the line on the Jpanel when dragging the mouse
    primarykey
    data
    text
    <p>I want to draw 2 (or more ) lines on JPanel when the mouse drags. When i use <code>super.paintComponent(g)</code> in my code, I couldn't draw 2 lines on the panel, however when I don't use <code>super.paintComponent(g)</code>;, the result is ugly, like the pic below :</p> <p><img src="https://i.stack.imgur.com/tR5Jv.jpg" alt="enter image description here"></p> <p>I understand why the lines behaved like that. </p> <p>How could I draw the lines on the Jpanel when dragging the mouse? BTW, the line drawn by <code>g2d.draw(line2d)</code> sometimes it's not the smooth line (pic below)</p> <p><img src="https://i.stack.imgur.com/pOfs7.jpg" alt="enter image description here"></p> <p>My codes so far :</p> <pre><code>import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; public class LineDrawing extends JPanel implements MouseMotionListener, MouseListener{ Point point1; Point point2; Line2D line2d; public LineDrawing(){ super(); addMouseListener(this); addMouseMotionListener(this); } @Override public void paintComponent(Graphics g){ //super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; if(point1!=null &amp;&amp; point2!=null){ g2d.setPaint(Color.RED); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(line2d); } } @Override public void mouseDragged(MouseEvent e) { point2 = e.getPoint(); line2d = new Line2D.Double(point1, point2); repaint(); } @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { point1 = e.getPoint(); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } public static void main(String a[]){ EventQueue.invokeLater(new Runnable(){ @Override public void run() { JFrame frame = new JFrame(); LineDrawing linedraw= new LineDrawing(); frame.add(linedraw); frame.setSize(500,500); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } }); } </code></pre> <p>}</p>
    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.
 

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