這是我的測試類:如何向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