-2

我试图让这段代码根据我原来的 Box 类打印出新的盒子,但我卡住了。我不确定我需要在我的网格类中指定哪些变量。我也不知道在下一堂课上放什么。

public void actionPerformed(ActionEvent evt)  {
    // maybe do stuff here
    repaint(); 
  }

这是我的两个课程。

---代码自第一次回复后已更新---

盒子类

import java.awt.*;

public class Box{

  int upperLeftX = 0;
  int upperLeftY = 0;
  int height = 20;
  int width = 20;
  Color color = Color.RED;

  //constructor
  public Box(int i, int j, int k, int l, Color m) {
    upperLeftX = i;
    upperLeftY = j;
    height = k;
    width = l;
    color = m;
  }

  // paints the box on screen
  public void display(Graphics g)
  {
    g.setColor(color);
    g.fillRect(upperLeftX,upperLeftY,width, height);
  }

  // getters and setters
  public int getUpperLeftX() {
    return upperLeftX;
  }

  public void setUpperLeftX(int upperLeftX) {
    this.upperLeftX = upperLeftX;
  }

  public int getUpperLeftY() {
    return upperLeftY;
  }

  public void setUpperLeftY(int upperLeftY) {
    this.upperLeftY = upperLeftY;
  }

  public int getHeight() {
    return height;
  }

  public void setHeight(int height) {
    this.height = height;
  }

  public int getWidth() {
    return width;
  }

  public void setWidth(int width) {
    this.width = width;
  }

  public Color getBoxColor() {
    return color;
  }

  public void setBoxColor(Color color) {
    this.color = color;
  }

}

网格类

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Grid extends Applet implements ActionListener{
  // declare variables here
  public void actionPerformed(ActionEvent evt)  {
    // maybe do stuff here
    repaint(); 
  }

  public void paint(Graphics g)   {   
    Box box1 = new Box(0,0,40,40,Color.WHITE);  
    box1.display(g);
    // do more stuff here
    Box box2 = new Box(40,40,40,40,Color.WHITE); 
    box2.display(g);
  }

}
4

1 回答 1

1

首先,Box不应该扩展Applet。事实上,它可能根本不应该扩展任何东西。它应该只作为有关盒子的一些数据的存储容器。这不会影响任何事情,只是令人困惑且没有意义。

其次,正如 Dan455 所指出的,Box构造函数中的赋值顺序错误。这不会造成任何伤害,只是传递给构造函数的参数会被神秘地忽略,而且看起来每个Box都是用new Box(0, 0, 20, 20).

第三,至于ActionListener,你不需要添加它,除非你有响应的东西ActionEvent。如果盒子的排列需要改变,你应该有一个盒子数组,所有的盒子都被绘制进去了paint,如果盒子的显示需要更新,你可以修改数组并调用repaint,它会paint尽快调用。

于 2013-07-25T19:24:35.157 回答