简体   繁体   中英

How to divide a JPanel into left and right segments?

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.

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

如果使用JSPlitPane ,则非常容易。

there are two ways

  • use GridLayout

  • use JSplitPane (with hidden divider)

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

使用JSplitPane或GridLayout

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);
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
JPanel example = new JPanel(new GridLayout(1,2));
example.add(p1);
example.add(p2);
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class Display{

JFrame frame=new JFrame("Drawing");
North north;
South south;
East east;
West west;
Center center;
public  int width=600,height=600;

public Display() {
    // TODO Auto-generated constructor stub
    frame.setSize(width,width);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(true);

    north=new North(frame);
    south=new South(frame);
    east=new East(frame);
    west=new West(frame);
    center=new Center(frame);

    frame.setLayout(new BorderLayout());


JSplitPane pane2=new JSplitPane(JSplitPane.VERTICAL_SPLIT,west,east);

frame.add(pane2);

    frame.setVisible(true);

  }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM