将JPanel添加到JFrame

我有一个程序,其中JPanel添加到JFrame:

public class Test{ Test2 test = new Test2(); JFrame frame = new JFrame(); Test(){ ... frame.setLayout(new BorderLayout()); frame.add(test, BorderLayout.CENTER); ... } //main ... } public class Test2{ JPanel test2 = new JPanel(); Test2(){ ... } } 

我收到一个错误,要求我将’panel’的类型更改为’component’。 我修复此错误? 它要我做:Component panel = new Component();

 public class Test{ Test2 test = new Test2(); JFrame frame = new JFrame(); Test(){ ... frame.setLayout(new BorderLayout()); frame.add(test, BorderLayout.CENTER); ... } //main ... } //public class Test2{ public class Test2 extends JPanel { //JPanel test2 = new JPanel(); Test2(){ ... } 

干得好

 public class Test{ public Test(){ design(); }//end Test() public void design(){ JFame f = new JFrame(); f.setSize(int w, int h); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setVisible(true); JPanel p = new JPanel(); f.getContentPane().add(p); } public static void main(String[] args){ EventQueue.invokeLater(new Runnable(){ public void run(){ try{ new Test(); }catch(Exception e){ e.printStackTrace(); } } ); } } 

不要让你的Test2类包含JPanel,你应该让它成为JPanel的子类:

 public class Test2 extends JPanel { Test2(){ ... } 

更多细节:

JPanel是Component的子类,因此任何以Component作为参数的方法也可以将JPanel作为参数。

较旧的版本不允许您直接添加到JFrame; 你必须使用JFrame.getContentPane()。add(Component)。 如果您使用的是旧版本,这可能也是一个问题。 较新版本的Java可以直接调用JFrame.add(Component)。

 Test2 test = new Test2(); ... frame.add(test, BorderLayout.CENTER); 

你确定吗? test不是一个组件! 为了做你想做的事,你应该让Test2扩展JPanel

你的Test2类不是一个Component ,它有一个与之不同的Component

要么你做的事情

 frame.add(test.getPanel() ); 

在为类中的面板引入getter之后,或者确保Test2类成为Component (例如,通过扩展JPanel