1

如何添加绘图 ii 一个 Japplet 而不是用新的替换它?我正在使用 repaint() 但它所做的只是替换我现有的矩形。添加另一个矩形而不是替换它的正确代码是什么?

说我有这个代码:(这个代码不是我的)

import java.applet.Applet;
import java.awt.*;

public class MoveBox extends Applet
{
   private int x = 20, y = 20;
   private int width = 10, height = 10;
   private int inc = 5;
   private Color myColor = Color.red;

   private Button up = new Button("Up");
   private Button down = new Button("Down");
   private Button left = new Button("Left");
   private Button right = new Button("Right");
   private Button increase = new Button("[+]");
   private Button decrease = new Button("[-]");

   // init method
   public void init()
   {
      Panel buttons = new Panel();
      buttons.setLayout(new FlowLayout());
      buttons.add(up);
      buttons.add(down);
      buttons.add(left);
      buttons.add(right);
      buttons.add(increase);
      buttons.add(decrease);

      setLayout(new BorderLayout());
      add("South", buttons);
   }
   // public methods
   public boolean action(Event e, Object o)
   {
      if (e.target == up)
         return handleUp();
      else if (e.target == down)
         return handleDown();
      else if (e.target == left)
         return handleLeft();
      else if (e.target == right)
         return handleRight();
      else if (e.target == increase)
         return handleIncrease();
      else if (e.target == decrease)
         return handleDecrease();
      else
         return super.action(e, o);
   }
   public void paint(Graphics g)
   {
      g.setColor(myColor);
      g.fillRect(x,y,width,height);
   }
   // private methods
   private boolean handleUp()
   {
      y = y - inc;
      repaint();
      return true;
   }
   private boolean handleDown()
   {
      y = y + inc;
      repaint();
      return true;
   }
   private boolean handleRight()
   {
      if (x < size().width)
         x = x + inc;
      else
         x = 0;
      repaint();
      return true;
   }
   private boolean handleLeft()
   {
      if (x > 0)
         x = x - inc;
      else
         x = size().width;
      repaint();
      return true;
   }
   private boolean handleIncrease()
   {
      width += 5;
      height += 5;
      repaint();
      return true;
   }
   private boolean handleDecrease()
   {
      if (width > 5)
      {
         width -= 5;
         height -= 5;
      }
      repaint();
      return true;
   }
}

当我按下按钮时,如何添加另一个矩形,向上、向下、向左和向右?

4

3 回答 3

3

绘制到 aBufferedImage并将其显示在 a 中JLabel。更新后,致电label.repaint()查看更改。EG 如Do Doodle中所见。

于 2012-12-16T09:51:19.817 回答
1

将您要绘制的东西存储在一个集合中(例如,您的两个矩形的坐标),调用repaint(),并让您的paintComponent()方法遍历该对象的集合以进行绘制并一一绘制。

于 2012-12-16T09:42:43.053 回答
1
于 2012-12-16T09:43:31.447 回答