JSplitPane Component in Java

May 29, 2020
Tutorials
jsplitpane in java

This is a tutorial that will teach you about creating a program that will have a JSplitPane Component in Java. A JSplitPane is used to let the user divides the two components. It can be resized by the user at will.

So, now let’s start this tutorial!

1. Open JCreator or NetBeans and make a java program with a file name of jSpliPaneComponent.java.

2. Import the following packages:

import java.awt.*;//used to access the Dimension class
import javax.swing.*; //used to access the JFrame, JLabel, JTextField, and JSplitPane component

3. Initialize your variable in your Main, variable frame for JFrame, variable text for JTextField, and variable label for JLabel. The text and label components will then be put inside the JSplitPane.

JFrame frame = new JFrame("JSplitPane Component");
 JTextArea text = new JTextArea("Campcodes is the best!");
 JLabel label = new JLabel("This is Engr. Lyndon Bermoy");

To have the size of the label and text, we will use the setMinimumSize method with the Dimension class having its width and height.

text.setMinimumSize(new Dimension(200, 200));
label.setMinimumSize(new Dimension(200, 200));

4. Now, we will use the JSplitPane to divide the label and text into two panes. Have this code below:

JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, text, label);

The JSplitPane is aligned from left to right using the horizontal alignment of the syntax HORIZONTAL_SPLIT. When we align them from top to bottom, we will use the VERTICAL_SPLIT. Take note that the text as JTextField and label as the JLabel was put inside the JSplitPane to divide the components into two.

5. Now, add the JSplitPane variable to the frame using the default BorderLayout of Center position of the getContentPane method. Finally, set the size, visibility, and the close operation of the frame. Copy this code below:

frame.getContentPane().add(sp, "Center");
 
 frame.setSize(450, 200);
 frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

Output:

jsplitpane in java


Here’s the full code of this tutorial:

import java.awt.*;//used to access the Dimension class
import javax.swing.*; //used to access the JFrame, JLabel, JTextField, and JSplitPane component
 
 
public class jSplitPaneComponent {
 
 
  public static void main(String args[]) {
 
    JFrame frame = new JFrame("JSplitPane Component");
    JTextArea text = new JTextArea("Campcodes is the best!");
    JLabel label = new JLabel("This is Engr. Lyndon Bermoy");
 
    text.setMinimumSize(new Dimension(200, 200));
    label.setMinimumSize(new Dimension(200, 200));
 
    JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, text, label);
 
 
    frame.getContentPane().add(sp, "Center");
 
     frame.setSize(450, 200);
     frame.setVisible(true);
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
 
 
  }
}

 

 

Facebook Comments

Leave a Reply

Your email address will not be published.