2012-09-12 69 views
1

我有一個JFrame A的子類。我有另一個B類,它是A的子類。我想將新組件添加到框架B(如JButton)。我的代碼如下:如何將組件添加到JFrame子類的子類中

public B() extends A { 
    //Calling super class constructor 
    super(); 

    //Creating and adding a button 
    JButton btn = new JButton(); 
    this.add(btn); 

    //other codes 
} 

當我顯示框架時,不添加按鈕,只顯示超類框架及其組件。我怎樣才能將這些按鈕添加到子類B的框架中?

更新:這裏是我的代碼的精簡版。我在超類ListObjects中使用了BorderLayout。

package assignment2; 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class ListAndModifyCustomer extends ListObjects { 

public ListAndModifyCustomer() { 
    //Calling super class constructor 
    super("Customers"); 

    //Adding listener to the ok button 
    super.selectBtn.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      //codes to create another JFrame 

      dispose(); //Closing the frame 
     } 
    }); 

    //Adding button to the panel 
    super.panel.add(new JButton("NO")); 

    JPanel jp = new JPanel(); 
    jp.add(super.selectBtn); 

    super.add(jp, BorderLayout.SOUTH); 
} 
} 
+3

我們需要一點點信息。你可以發佈一個[SSCCE](http://www.sscce.org)來說明你在做什麼?特別是,我想知道你使用的是什麼'LayoutManager'? –

回答

0

我發現如果我們在子類中創建一個面板,並將所有項目添加到該面板,並將該面板添加到超類的框架,那麼組件將變得可見。

0

this.getContentPane().add(btn)
我無法評論更多,因爲沒有關於使用什麼組件,佈局等的信息。

+0

不,不需要明確添加到contentPane - 請閱讀frame.add的API文檔 – kleopatra

0

最可能的原因是BorderLayout。 A BorderLayout只能在每個位置包含一個組件。如果您未指定位置,則將使用CENTER位置。

所以,如果你的兩個類ListObjectsListAndModifyCustomer類做add呼叫而不指定位置,只有seceond組件將是可見的(並添加)。

+0

可以演示指定的位置,因爲我無法掌握它@robin –

+0

@ nick-s請參閱[教程](http: //docs.oracle.com/javase/tutorial/uiswing/layout/border.html) – Robin

相關問題