2015-10-20 98 views
3

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

+1

'JFrame'默認使用'BorderLayout',這意味着只有最後一個組件被放置在默認/'CENTER'位置。另外,在做任何自定義繪畫之前,你應該調用'super.paintComponent(g)' – MadProgrammer

回答

0

您可以嘗試使用一個循環:

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

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

JFrame使用BorderLayout默認情況下,這意味着只有最後一個組件被放置在缺省的/ CENTER位置。

首先更改佈局管理器。

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

    frame.setLayout(new GridLayout(1, 3)); 
    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); 
} 

看看Laying Out Components Within a Container更多細節

這是假設,當然,你要保持你的形狀,每個實例在它自己的組件。如果您希望形狀以某種方式進行交互或重疊,則最好創建一個JComponent,它可以自己繪製不同的形狀。

看一看2D Graphics更多的想法

此外,你應該叫super.paintComponent(g)你做任何自定義塗裝前

看一看Painting in AWT and SwingPerforming Custom Painting更多細節

0

我實例化Shape1類3次並將它們添加到框架中。但形狀只畫一次,我怎麼畫3次?

如果您想要在面板中隨機定位組件(即您的示例中的JFrame的內容窗格),則需要將面板的佈局設置爲空。這意味着您需要手動確定組件的大小/位置。你開始添加形狀到幀之前

frame.setLayout(null); 

所以,你會需要添加。

但是,通常使用空佈局從來都不是好主意。因此,我建議您使用Drag Layout,因爲它旨在替換這種情況下的空佈局。

相關問題