1

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

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Exactly... this code : GUI6.gui6.jSplitPane1.setRightComponent(null); GUI6.gui6.jSplitPane1.setLeftComponent(null); was the key of problem. I tried method removeAll() before. But this is the best way. Thank you so much !

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.