gpt4 book ai didi

java - 如何向JComponent添加多个对象?

转载 作者:行者123 更新时间:2023-12-02 08:44:30 27 4
gpt4 key购买 nike

这是我的测试人员类(class):

public void start() {
// We do our drawing here
JFrame frame = new JFrame("Animation");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));


frame.setVisible(true);
}

Shape1 类:

public class Shape1 extends JComponent{
protected double x, y, r;
protected double height, width;
protected Color col;
protected int counter;

public Shape1(double x, double y, double r) {
this.x = x - 2*r;
this.y = y - r;
this.r = r;
this.width = 4*r;
this.height = 2*r;

this.col = new Color((int)(Math.random() * 0x1000000));
}

public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
draw(g2);
}

public void draw(Graphics2D g2){
Ellipse2D.Double face = new Ellipse2D.Double(this.x, this.y, this.width, this.height);

g2.setColor(this.col);
g2.fill(face);
}
}

我实例化 Shape1 类 3 次并将它们添加到框架中。但是形状只画了一次,怎么画3次呢?

最佳答案

您可以尝试使用循环:

List<Shape1> shapes = new ArrayList<>();

@Override
protected void paintComponent(Graphics g) {
super.paintCompoent(g);
for (Shape1 s : shapes) {
s.draw(g);
}
}

关于java - 如何向JComponent添加多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com