How can we hide left/right pane of a JSplitPane programmatically in Java?


A JSplitPane is a subclass of JComponent class that allows us to arrange two components side by side horizontally or vertically in a single pane. The display areas of both components can also be adjusted at the runtime by the user. The important methods of JSplitPane are remove(), removeAll(), resetToPreferredSizes() and setDividerLocation(). A JSplitPane can generate a PropertyChangeListener interface. We can hide one of the panes (left or right) programmatically by click on the left button or right button and can generate action listeners for those buttons.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JSplitPaneHideTest extends JFrame {
   private JButton leftBtn, rightBtn;
   private JSplitPane jsp;
   public JSplitPaneHideTest() {
      setTitle(" JSplitPaneHide Test");
      leftBtn = new JButton("Left Button");
      rightBtn = new JButton("Right Button");
      jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftBtn, rightBtn);
      jsp.setResizeWeight(0.5);
      // Implemention code to hide left pane or right pane
      ActionListener actionListener = new ActionListener() {
         private int loc = 0;
         public void actionPerformed(ActionEvent ae) {
            JButton source = (JButton)ae.getSource();
            if(jsp.getLeftComponent().isVisible() && jsp.getRightComponent().isVisible()) {
               loc = jsp.getDividerLocation();
               jsp.setDividerSize(0);
               jsp.getLeftComponent().setVisible(source == leftBtn);
               jsp.getRightComponent().setVisible(source == rightBtn);
            } else {
               jsp.getLeftComponent().setVisible(true);
               jsp.getRightComponent().setVisible(true);
               jsp.setDividerLocation(loc);
               jsp.setDividerSize((Integer) UIManager.get("SplitPane.dividerSize"));
            }
         }
      };
      rightBtn.addActionListener(actionListener);
      leftBtn.addActionListener(actionListener);
      add(jsp, BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JSplitPaneHideTest();
   }
}

Output





Updated on: 10-Feb-2020

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements