这是我的测试类:如何向JComponent添加多个对象?
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次?
'JFrame'默认使用'BorderLayout',这意味着只有最后一个组件被放置在默认/'CENTER'位置。另外,在做任何自定义绘画之前,你应该调用'super.paintComponent(g)' – MadProgrammer