Setting divider location on a JSplitPane doesn't work

别来无恙 提交于 2019-11-27 15:06:47
mKorbel

nothing complicated in this case, with rules

1) PrefferedSize must returns Childs not as I wrong to set in my case too :-), then my answer isn't @kleopatra resist too

2) put everything about rezize, size, whatever for JSplitPane into invokeLater() .

.
import java.awt.*;
import javax.swing.*;

public class JSplitProblem extends JFrame {

    private static final long serialVersionUID = 1L;
    private JSplitPane mainSplittedPane;

    public JSplitProblem() {
        JPanel upperPanel = new JPanel();
        upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.X_AXIS));
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        JPanel red = new JPanel();
        red.setBackground(Color.red);
        leftPanel.add(red);
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        JPanel blue = new JPanel();
        blue.setBackground(Color.blue);
        rightPanel.add(blue);
        upperPanel.add(leftPanel);
        upperPanel.add(rightPanel);
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(Color.black);

        mainSplittedPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel, bottomPanel);
        mainSplittedPane.setOneTouchExpandable(true);
        mainSplittedPane.setDividerLocation(0.5);

        add(mainSplittedPane);
        setPreferredSize(new Dimension(400, 300));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(true);
        setVisible(true);
        pack();
        restoreDefaults();
    }

    private void restoreDefaults() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                mainSplittedPane.setDividerLocation(mainSplittedPane.getSize().height /2);
                //mainSplittedPane.setDividerLocation(mainSplittedPane.getSize().width /2);
            }
        });
    }

    public static void main(String[] args) {
        JSplitProblem jSplitProblem = new JSplitProblem();
    }
}

If you want both halves of the split pane to share in the split pane's extra or removed space, set the resize weight to 0.5: (Tutorial)

JSplitPane mainSplittedPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperPanel,bottomPanel);
mainSplittedPane.setOneTouchExpandable(true);
mainSplittedPane.setResizeWeight(0.5);                            

I'm not sure, but I think you should try to pack() your frame. And if that doesn't work, try to reset the divider location after you packed the frame.

Just add the code below, and that will be fairly enough.

mainSplittedPane.setResizeWeight(0.5);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!