0

How can I paint continous line in JPanal made by rectengle.

My Code:

 @Override
    public void mousePressed(MouseEvent e) {
          x = e.getX();
          y = e.getY();
          points.add(new Point(x, y));
          repaint();
    }

@Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
        g2d.setColor(Color.BLACK);
        drawRectangles(g2d);
        drawLines(g2d);
    }

points is a List to store my rectengle.

I want to draw continous line on pressed button, but all I've got is one rectengle per click.

    private void drawRectangles(Graphics2D g2d) {
        int x, y;
        for (Point p : points) {
            x = (int) p.getX();
            y = (int) p.getY();
            g2d.fillRect(x, y, 10, 10);
        }
    }
Demon4i
  • 27
  • 7
  • 2
    I think you are supposed to use a `MouseMotionListener` rather than a `MouseListener`. `mousePressed` only gives you the location of the actual pressing, not the locations of the mouse when it's dragged. – RealSkeptic Nov 13 '19 at 16:28
  • See [Custom Painting Approaches](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for a working example. – camickr Nov 13 '19 at 17:52

1 Answers1

1

Try adding a MouseMotionListener instead of MouseListener, and you can incorporate the MouseDragged method to paint. See the documentation here.

Daniel
  • 11
  • 1