In this example on how to get or set the location of the divider in a JSplitPane
component of a Java Desktop Application.
In order to do that you have to follow these steps:
- Create a new
JFrame
. - Call
frame.getContentPane().setLayout(new FlowLayout())
to set flow layout for the frame. - Create two String arrays that will containt the contents of the two areas of the
JSplitPane
. - Create two
JScrollPane
components. - Create a new
JSplitPane
with the aboveJScrollPane
components in each side. - Call
splitPane.getDividerLocation()
to get the divider location. - Call
splitPane.setDividerLocation()
to set the divider location.
Let’s see the code snippet that follows.
package com.javacodegeeks.snippets.desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class GetSetDividerLocationInJSplitPane {
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Split Pane Example");
// Display the window.
frame.setSize(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
String[] options1 = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JList list1 = new JList(options1);
String[] options2 = { "Car", "Motorcycle", "Airplane", "Boat" };
JList list2 = new JList(options2);
JScrollPane scrollPane1 = new JScrollPane(list1);
JScrollPane scrollPane2 = new JScrollPane(list2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane1, scrollPane2);
splitPane.setPreferredSize(new Dimension(400, 200));
// get the current divider location (pixels from left edge)
int dividerLocation = splitPane.getDividerLocation();
System.out.println("Divider Location before: " + dividerLocation);
// set new divider location
splitPane.setDividerLocation(150);
System.out.println("Divider Location after: " + splitPane.getDividerLocation());
frame.getContentPane().add(splitPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This was an example on how to get and set the divider location in JSplitPane component in Java.