Search code examples
javaswingmouseclick-event

Drawing every Rectangle on mouseclick instead of setLocation


Currently, this code segment moves the current rectangle already drawn on a frame by mouse click. The coordinates of that click go to variable x and y. Wherever it is clicked on the frame, the rectangle will move to that place. I want it to just draw a new rectangle instead, so for example when i click 10 times randomly on the screen there will be 10 rectangles. How do you do this?

public void moveRectangleTo(int x, int y)
       {
          box.setLocation(x, y);
          repaint();      
       }

FULL CODE: RectangleComponent Class

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

public class RectangleComponent2 extends JComponent
{
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleComponent2()
   {  
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   public void moveRectangleTo(int x, int y)
   {
      box.setLocation(x, y);
      repaint();      
   }
}

Rectangle Frame Class:

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

public class RectangleFrame2 extends JFrame {
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;
   private RectangleComponent2 scene;

   class MousePressListener implements MouseListener {  
      public void mousePressed(MouseEvent event) {  
         int x = event.getX();
         int y = event.getY();
         scene.moveRectangleTo(x, y);
      }
      public void mouseReleased(MouseEvent event) {}
      public void mouseClicked(MouseEvent event) {}
      public void mouseEntered(MouseEvent event) {}
      public void mouseExited(MouseEvent event) {}
   }

   public RectangleFrame2() {
      scene = new RectangleComponent2();
      add(scene);

      setSize(FRAME_WIDTH, FRAME_HEIGHT);

      MouseListener listener = new MousePressListener();
      scene.addMouseListener(listener);
   }
} 

Solution

  • You need to keep a list of boxes.

    private List<Rectangle> boxes = new ArrayList<>();
    

    On the mouse click, instead of moving the box, add a new one:

    public void addRectangleAt(int x, int y)
       {
          Rectangle boxNew = new Rectangle(x, y, BOX_WIDTH, BOX_HEIGHT);
          boxes.add(boxNew);
          repaint();      
       }
    

    Then in your paintComponent() method, iterate through you boxes list and paint each one.