javaswingjsplitpane

How to move JSplitPane's divider when I double-clicked it?


I want to move JSplitPane's divider to center if I double-click the divider.

So I added MouseListener to JSplitPane but it didn't work.

It works only when I double-clicked other JSplitPane's space without the divider.

Is there any way to work as I want?

Here is the code I failed

splitPane.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        //super.mouseClicked(e);
        splitPane.setDividerLocation(0.5);
    }
});

(it work same when I use MouseListener)


Solution

  • The reason your code doesn't work is that the JSplitPane itself does not recieve the click event.

    Instead, the UI class of JSplitPane does.

    This code works:

    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, component1, component2);
    
        SplitPaneUI spui = split.getUI();
        if (spui instanceof BasicSplitPaneUI) {
            ((BasicSplitPaneUI) spui).getDivider().addMouseListener(new MouseAdapter() {
    
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    if (arg0.getClickCount() == 2) {
                        split.setDividerLocation(0.5);
                    }
                }
            });
        }