Java Swing Tutorial - Java Swing JSeparator








A JSeparator is a separator between two components.

A JSeparator is often used in a menu to separate groups of related menu items.

We can create a horizontal or a vertical JSeparator by specifying its orientation.

The following code creates a horizontal separator. By default, the type is horizontal.

JSeparator hs  = new JSeparator(); 

The following code creates a vertical separator.

JSeparator vs  = new JSeparator(SwingConstants.VERTICAL);

setOrientation() and getOrientation() methods to set and get the orientation of the JSeparator.

import javax.swing.JFrame;
import javax.swing.JSeparator;
//from   w w  w  . j  a  v  a  2  s.  c  o m
public class Main {

  public static void main(String[] a){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    frame.add(new JSeparator(JSeparator.VERTICAL));

    frame.setSize(300, 200);
    frame.setVisible(true);
  }


}




Add Separator to Menu

import java.awt.event.KeyEvent;
/*  w  w  w .  ja v a  2s .  c  o m*/
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class Main {

  public static void main(final String args[]) {
    JFrame frame = new JFrame("MenuSample Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menuBar = new JMenuBar();

    // File Menu, F - Mnemonic
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);

    // File->New, N - Mnemonic
    JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
    fileMenu.add(newMenuItem);

    // Separator
    fileMenu.addSeparator();

    // File->Save, S - Mnemonic
    JMenuItem saveMenuItem = new JMenuItem("Save", KeyEvent.VK_S);
    fileMenu.add(saveMenuItem);

    frame.setJMenuBar(menuBar);
    frame.setSize(350, 250);
    frame.setVisible(true);
  }
}




Customizing JSeparator Look and Feel

Property StringObject Type
Separator.backgroundColor
Separator.foregroundColor
Separator.insetsInsets
Separator.thicknessInteger
SeparatorUIString