How to divide a JPanel into left and right segments?

14,033

Solution 1

If there is no need to resize them, you can simply use a BorderLayout and insert your panels in the BorderLayout.EAST and BorderLayout.WEST:

JPanel panel = new JPanel( new BorderLayout() );
panel.add( leftPanel, BorderLayout.WEST );
panel.add( rightPanel, BorderLayout.EAST );

You could also consider using a JSplitPane which allows to resize the UI:

JSplitPane pane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, 
                                  leftPanel, rightPanel );

Solution 2

Use a JSplitPane or a GridLayout

Solution 3

there are two ways

  • use GridLayout

  • use JSplitPane (with hidden divider)

Solution 4

JPanel panel = new JPanel(new BorderLayout());
panel.add(c1, BorderLayout.WEST);
panel.add(c2, BorderLayout.EAST);

JPanel panel = new JPanel(new GridLayout(1, 2));
panel.add(c1);
panel.add(c2);

Solution 5

You can use SplitPane as Costis Aivalis suggested.
Or
Use Border Layout Manager on JPanel.
Put your left side components in WEST side and put your right side components in EAST side of layout manager.

JPanel panel = new JPanel(new BorderLayout());
panel.add(c1, BorderLayout.WEST);
panel.add(c2, BorderLayout.EAST);
Share:
14,033
SuperStar
Author by

SuperStar

Caffeine is my poison. What is yours ?

Updated on June 13, 2022

Comments

  • SuperStar
    SuperStar almost 2 years

    I want to divide a JPanel into left and right segments. How do I do that ? After that, I will place panels in the left and right half.

  • SuperStar
    SuperStar about 11 years
    error - The constructor JSplitPane(JPanel, JPanel) is undefined
  • SuperStar
    SuperStar about 11 years
    did that. It messes up the gui, small buttons in left panel take the whole left side and the other components that should be on left side are not visible
  • Mohan Raj B
    Mohan Raj B about 11 years
    JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel). Try this one
  • samvdst
    samvdst about 11 years
    how many components do you have on the left side? if you want more than one you have to split the left panel again.
  • Eng.Fouad
    Eng.Fouad about 11 years
  • SuperStar
    SuperStar about 11 years
    Three panels on the left side. Each panel has some components like buttons, text fields etc.
  • samvdst
    samvdst about 11 years
    so for the left panel you could use GridLayout(3,1) and then add the buttons, text fields.. this will give you three lines. if you want to have the buttons and text fields horizontally you can use GridLayout(1,3) this will give you three columns