在mouseclick上绘制每个Rectangle而不是setLocation

时间:2017-07-23 19:00:48

标签: java swing mouseclick-event

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

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();      
   }
}

完整代码: RectangleComponent类

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);
   }
} 

矩形框架类:

log_errors on
error_log  /home/account/public_html/error.log

1 个答案:

答案 0 :(得分:3)

您需要保留一个方框列表。

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()方法中,遍历您的方框列表并绘制每个方法。