在鼠标点击而不是 setLocation 上绘制每个矩形

Drawing every Rectangle on mouseclick instead of setLocation

目前,此代码段通过鼠标单击移动已在框架上绘制的当前矩形。该点击的坐标转到变量 xy。无论在框架上的哪个位置单击,矩形都会移动到该位置。我希望它只绘制一个新矩形,例如,当我在屏幕上随机单击 10 次时,将出现 10 个矩形。你是怎么做到的?

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

完整代码: 矩形组件 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();      
   }
}

矩形框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);
   }
} 

您需要保留一个盒子列表。

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

点击鼠标,不移动框,而是添加一个新框:

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

然后在您的 paintComponent() 方法中,遍历您的框列表并绘制每个框。