Search code examples
javaswinguser-interfacejsplitpane

java: Problem with JSplitpane


I would like to have a jsplitPane and swap right component by left component while running my program. I set division location about 0.2. when I swapped my left component and right component and set division location about 0.8; there is a problem with jSplitPane. It is locked and I can't move divisor. also after that; when I try to assign another component to right or left side of JSplitPane, the components appear bollixed. I tried by setDivisionLocation() method before swapping right and left component; but it is not effective. and also repaint() method.... please guide me

regards...sajad


Solution

  • I think your problem is that you add a component twice (that could really make thinks look strange). E.g you do something like: split.setLeftComponent(split.getRightComponent()).

    So when you do the swap you need to remove the components first:

    private static void swap(JSplitPane split) {
        Component r = split.getRightComponent();
        Component l = split.getLeftComponent();
    
        // remove the components
        split.setLeftComponent(null);
        split.setRightComponent(null);
    
        // add them swapped
        split.setLeftComponent(r);
        split.setRightComponent(l);
    }
    

    And the demo is here (also moves the divider location):

    before after

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");
    
        final JSplitPane split = new JSplitPane(
                JSplitPane.HORIZONTAL_SPLIT, 
                new JLabel("first"), 
                new JLabel("second"));
    
        frame.add(split, BorderLayout.CENTER);
        frame.add(new JButton(new AbstractAction("Swap") {
            @Override
            public void actionPerformed(ActionEvent e) {
                // get the state of the devider
                int location = split.getDividerLocation();
    
                // do the swap
                swap(split);
    
                // update the devider 
                split.setDividerLocation(split.getWidth() - location 
                        - split.getDividerSize());
            }
    
    
        }), BorderLayout.SOUTH);
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }