2012-09-12 70 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

相关问题