2011-10-13 20 views
1
import java.awt.*; 
import javax.swing.*; 
import java.awt.geom.*; 

public class Box { 
    public static void main(String[] args){ 
     BoxFrame frame = new BoxFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 

class BoxFrame extends JFrame{ 
    public BoxFrame(){ 
     setTitle("BoxGame"); 
     setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 
     DrawComponent[] component = new DrawComponent[4]; 
     component[0] = new DrawComponent(0, 0, 20, 20); 
     component[1] = new DrawComponent(400, 0, 20, 20); 

     add(component[0]); 
     add(component[1]);//here the problem is 
    } 
    public static final int DEFAULT_WIDTH = 600; 
    public static final int DEFAULT_HEIGHT = 400; 
} 

class DrawComponent extends JComponent{ 
    private double left; 
    private double top; 
    private double width; 
    private double height; 
    public DrawComponent(double l, double t, double w, double h){ 
     left = l; 
     top = t; 
     width = w; 
     height = h; 
    } 
    public void paintComponent(Graphics g){ 
     Graphics2D g2 = (Graphics2D) g; 
     Rectangle2D rect = new Rectangle2D.Double(left, top, width, height); 
     g2.draw(rect); 
     g2.setPaint(Color.BLUE); 
     g2.fill(rect); 
    } 
} 

這是我的代碼,它並不複雜。但是當我嘗試繪製兩個組件時,窗口只繪製一個。這段代碼,當我擺脫第一個組件時,窗口將繪製第二個組件。我已經看過了在的javadoc JFrame.add的方法,但沒有發現什麼錯誤,plz幫助我在JFrame中看不到一個組件

回答

5

的問題是,您使用的是JFrame這是一個BorderLayout的默認佈局管理器。當你的第二個組件是add時,它將取代第一個組件。 (兩者都被添加到CENTER單元格中。)

如果您想使用組件來顯示框,我建議您將它們放置在不重疊的位置。

否則,我建議你在同一個組件上繪製所有盒子。

+0

哦,thx非常。我再次忘記this.thx – cloud