2013-02-25 166 views
1

我有初始化一個JPanel。這裏的一個問題一個Swing的JPanel是我的代碼:`初始化與另一個

JPanel canvas = new JPanel(); 
    JPanel can = canvas; 
    System.out.println("COMPONENTS 1 :" + canvas.getComponentCount()); 
    System.out.println("COMPONENTS 1 :" + can.getComponentCount()); 
    JTextField txt = new JTextField(); 
    txt.setBounds(100, 100, 200, 30); 
    can.add(txt); 
    System.out.println("COMPONENTS 2 :" + canvas.getComponentCount()); 
    System.out.println("COMPONENTS 2 :" + can.getComponentCount()); 

`

輸出爲:

COMPONENTS 1 :0 
COMPONENTS 1 :0 
COMPONENTS 2 :1 
COMPONENTS 2 :1 

我想要什麼:

COMPONENTS 1 :0 
COMPONENTS 1 :0 
COMPONENTS 2 :0 
COMPONENTS 2 :1 

回答

2

隨着線
JPanel can = canvas;

您並未創建新的JPanel對象。你正在做can,指向畫布指向的同一個JPanel對象。 Canvas只是一個指向JPanel內存地址的指針。實際上,can和canvas是完全相同的JPanel。如果您希望能夠獨立修改它們,您希望創建一個新的JPanel實例。