javaswinguser-interfacejsplitpane

Set JSplitPane divider location from the right


As far as I know, the setDivider() method of JSplitPane can take an int which is an absolute position from the left. For example, someSplitPane.setDivider(120); will set the divider 120px from the left. Is there any way I can do the same thing, but set the divider an absolute position from the right?

Simple implementation:

public class Window extends JFrame {
    
    JSplitPane splitpane;
    
    public Window() {
        initComponents();
    }
    
    private void initComponents() {
        setTitle("Debugging");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(640, 480));
        
        splitpane = new JSplitPane();
        System.out.println(splitpane.getSize().width); // prints 0
        splitpane.setDividerLocation(splitpane.getSize().width - 120);
        getContentPane().add(splitpane);
    }
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            new Window().setVisible(true);
        });
    }
}

EDIT: I have written this code isolated from any existing code, and I reproduce the error. What looks to be happening is the JFrame is instantiating and appears on the desktop, and then about a second later, a 0 (from the commented print statement) is output to the console.


Solution

  • Assuming you create your GUI correctly by using the EDT you can add the following in the constructor of your class where you create the splitPane:

    SwingUtilities.invokeLater(() ->
    {
            Dimension d = splitPane.getSize();
            splitPane.setDividerLocation(d.width - 120);
    });
    

    This will add code to the EDT. So after the frame is visible and the split pane has been given a size, the divider location will be reset.