1

I'm new java GUI developer and I have a question.

Is possible to create a Jframe with multiples Jpanels? My idea is create a class with the components added in the JPanel and from another class create the JFrame adding multiples objects of the JPanel Class.

At the moment I'm doing test:

public class Principal {

    private JFrame window;

    public Principal(){

        window = new JFrame("Principal");        
    }

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

Child Class

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 Class

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);
    }
}
`
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
ruzD
  • 555
  • 1
  • 15
  • 29
  • 3
    *"Is possible to create a Jframe with multiples Jpanels?"* Yes. In fact, **most** real world GUIs have multiple panels. I use them to allow setting different layouts in different parts of the GUI. See [this example](http://stackoverflow.com/a/5630271/418556) that combines layouts. – Andrew Thompson Jul 21 '15 at 10:29
  • Ok, thank you. I going to read the example. – ruzD Jul 21 '15 at 14:39

1 Answers1

0

It is certainly possible to have multiple JPanels in a JFrame. You can get the component Container from the JFrame with getContentPane(), which in your example would work as

p.getFinestra().getContentPane();

To understand how to place your JPanels to the JFrame, you should study some Layouts. Here is a good resource and this site has many more: https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

For example to use a FlowLayout (the default one)

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);

And as a short lesson in English, the plural of child is children.

milez
  • 2,201
  • 12
  • 31
  • I already understand it. I have create the frame and I put the content panel and I add the components. You're right, child -> children :( – – ruzD Jul 21 '15 at 14:39