我试图让这段代码根据我原来的 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);
}
}