2015-07-21 44 views
1

我是新的Java GUI开发人员,我有一个问题。设计带有多个JPanels的JFrame?

是否可以使用多个Jpanel创建Jframe?我的想法是创建一个类,在JPanel中添加组件,并从另一个类创建JFrame,添加JPanel类的多个对象。

目前我在做测试:

public class Principal { 

    private JFrame window; 

    public Principal(){ 

     window = new JFrame("Principal");   
    } 

    /** 
    * @return the finestra 
    */ 
    public JFrame getFinestra() { 
     return window; 
    } 
}` 

子类

public class Childs { 

    private JPanel panel; 
    private JLabel text1; 

    public Childs(){ 
     panel = new JPanel(); 
     text1 = new JLabel(); 

     text1.setText("TEXT"); 
     panel.add(text1); 
    } 

    /** 
    * @return the panel 
    */ 
    public JPanel getPanel() { 
     return panel; 
    } 
} 

TestFrame类

public class TestFrame { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 

     Principal p = new Principal(); 
     Childs c = new Childs(); 
     Childs c2 = new Childs(); 

     p.getFinestra().add(c.getPanel()); 
     p.getFinestra().add(c2.getPanel()); 
     p.getFinestra().setVisible(true); 
    } 
} 
` 
+3

*“是否可以使用多个Jpanel创建Jframe?”*是的。事实上,**大多数**真实世界的GUI都有多个面板。我使用它们来允许在GUI的不同部分设置不同的布局。请参阅结合布局的[本示例](http://stackoverflow.com/a/5630271/418556)。 –

+0

好的,谢谢。我会读这个例子。 – ruzD

回答

0

这当然是可能有多个JPanels在JFram中即您可以从JFrame中有getContentPane(),这在你的例子会工作作为

p.getFinestra().getContentPane(); 

要了解如何将您的JPanel■将到JFrame,你应该学习一些Layout小号获取组件Container。这里是一个很好的资源,这个网站有更多的:https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

例如使用FlowLayout(默认的)

p.getFinestra().getContentPane().setLayout(new FlowLayout()); 
p.getFinestra().getContentPane().add(c); 
p.getFinestra().getContentPane().add(c2); 

//It is also a good habit to call pack() before setting to visible 
p.getFinestra().pack() 
p.getFinestra().setVisible(true); 

而且随着英语很短的教训,孩子的复数儿童

+0

我已经明白了。我创建了框架,并将内容面板添加到组件中。你是对的,孩子 - >孩子:( - – ruzD