bbariotti
bbariotti

Reputation: 41

How to organize my JPanel inside a JFrame?

I'm having trouble organizing JPanel inside a JFrame.

I have 3 JPanels and need to organize them as follows:

panel1 panel2

panel__3333333

However, can only horizontally align panel1 and panel2 as follows:

 groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
        .addComponent(PANEL1)
        .addComponent(PANEL2));
    groupLayout.setVerticalGroup(groupLayout.createParallelGroup()
        .addComponent(PANEL1)
        .addComponent(PANEL2));  

Thanks.

Upvotes: 1

Views: 1492

Answers (2)

zThulj
zThulj

Reputation: 149

I think you should use GridBagLayout instead of a grouplayout. It matches with your needs

See the oracle doc on gridbag layout here

Upvotes: 0

Clausiel
Clausiel

Reputation: 53

The easiest way to accomplish this is to house your JPanels inside of other JPanels.

Here is an example of what you might do:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//this is the main JPanel that will house all of your child JPanels
JPanel mainPanel= (JPanel)frame.getContentPane();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//this JPanel will house "panel1" and "panel2" on top and will go inside the main panel
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));

//add panel1 and panel2 to topPanel here

mainPanel.add(topPanel);

//add panel3 to mainPanel here

frame.pack();
frame.setVisible(true);

There are many different approaches to this, but I find this the easiest. Hope this helps!

Upvotes: 3

Related Questions