How to create splitpanes in java using JSplitPane?
Before going to see how we can create split panes first take a look, what the Split Pane actually is? It is nothing but a light weight Swing Container which separates components graphically. Split pane allows two components to be split inside a container, to split more than one component we need to nest split panes and components. The components which we split can be adjusted interactively by user.
To create split panes in java we can use the JSplitPane class which is inherited by JComponent class. Split panes are of two types Horizontal and Vertical , meaning Horizontal Split Pane divides components horizontally and the divider can be moved horizontally. Similarly Vertical split panes divides components vertically and divider can be moved vertically.
JSplitPane Constructors :
First is simple one as shown below creates a split pane with horizontally.
In the next constructor we can specify the orientation whether is is horizontal or vertical
public JSplitPane( int orientation )
where orientation will be either HORIZONTAL_SPLIT or VERTICAL_SPLIT
Third one is having extra setting which is used when we change the divider position , the child components should get re sized or not.
public JSplitPane( int orientation, int isContinuousLayout )
continuous layout property can be turned on or off , if we make it ON , the child components resized continuously when we change the divider position.
public JSplitPane( int orientation, Component leftComponent, Component rightComponent )
In above constructor components can also be specified.
In last constructor we can have all the settings i.e. orientation, continuousLayout , left component and right component.
public JSplitPane( int orientation , boolean continuousLayout, Component leftComponent, Component rightComponent )
Now lets see simple example , how we can create the split panes.
JPanel childPanel1 = new JPanel(); JPanel childPanel2 = new JPanel(); JLabel childLabel1 = new JLabel("Child Component 1 "); JLabel childLabel2 = new JLabel("Child component 2"); childPanel1.add( childLabel1 ); childPanel2.add( childLabel2 ); JSplitPane splitPaneExample = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, // Horizontal Split selected true, childPanel1, childPanel2); // Continuous Layout Property is true getContentPane().add(splitPaneExample);