作为初学者,每当我想在框架内添加图形形状时,我都会这样做:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, 10, 10);
g.fillOval(10,10,10,10);
}
如何在框架内自动绘制无限数量的形状?如果我按照上面的方式操作,我只有有限数量的形状(矩形、椭圆形,没有其他)。
我正在寻找不同的东西,例如,每当调用方法 addStuff(x, y)
时,它都会在坐标 x 和 y 处自动绘制“Stuff”,而无需编辑任何内容再次手动在 paintComponent
内。
我曾经使用 acm 包来做到这一点,而且很简单。就像下面的代码一样。
for (int i = 0; i < NCIRCLES; i++) {
double r = rgen.nextDouble(MIN_RADIUS, MAX_RADIUS);
double x = rgen.nextDouble(0, getWidth() - 2 * r);
double y = rgen.nextDouble(0, getHeight() - 2 * r);
GOval circle = new GOval(x, y, 2 * r, 2 * r);
circle.setFilled(true);
circle.setColor(rgen.nextColor());
add(circle);
}
正如您在上面所看到的,我可以添加任意数量的圆圈,我知道可能需要几页的时间来解释这一点,但我只想简要说明如何在不依赖 acm 包的情况下创建与上面的代码类似的内容.
最佳答案
我将使用抽象类来定义此行为。
abstract class OpalDraw {
protected int x1, y1, x2, y2;
protected OpalDraw(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
abstract public void draw(Graphics g);
}
class OpalOval {
public OpalOval(int x1, int y1, int x2, int y2) { super(x1,y1,x2,y1); }
public void draw(Graphics g) {
g.drawOval(x1,y1,x2,y1);
}
}
class OpalRect {
public OpalRect(int x1, int y1, int x2, int y2) { super(x1,y1,x2,y1); }
public void draw(Graphics g) {
g.drawRect(x1,y1,x2,y1);
}
}
然后在你的绘画容器中你就可以拥有
addOval(int x1, int y1, int x2, int y2) {
myDraws.add(new OpalOval(x1,x2,y1,y2);
}
addRect(int x1, int y1, int x2, int y2) {
myDraws.add(new OpalRect(x1,x2,y1,y2);
}
然后在paintComponent(Graphics)
中你可以
for(OpalDraw draw : myDraws) draw.draw(g);
关于java - 如何在paintComponent中自动添加形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7246871/