How can we set a background color to JSplitPane 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 set a background color to a JSplitPane by adding two different background colors to two panels first and pass these arguments to JSplitPane constructor.

Example

import javax.swing.*;
import java.awt.*;
public class JSplitPaneColorTest extends JFrame {
   private JSplitPane jsp;
   private JPanel panel1,panel2;
   public JSplitPaneColorTest() {
      setTitle("JSplitPane Example");
      panel1 = new JPanel();
      panel1.setBackground(Color.lightGray);
      panel2 = new JPanel();
      panel2.setBackground(Color.blue);
      jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
      jsp.setDividerSize(10);
      jsp.setResizeWeight(0.5);
      add(jsp);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setSize(400, 275);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JSplitPaneColorTest();
   }
}

Output

Updated on: 10-Feb-2020

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements