In this tutorial, we are going to learn how to apply borders using Swing BorderFactory class.

Swing BorderFactory :

BorderFactory is a Factory class which produces different types of borders (Border instances). Here I am going to show how to apply borders for swing components.

Swing BorderFactory Example:

MyBorderFrame.java
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

class MyBorderFrame extends JFrame {
    JButton ok, cancel;
    Container contentPane;
    JPanel panel;
    Font fontTitle;

    MyBorderFrame() {
        super("Border and Sizes Demo");

        panel = new JPanel();

        ok = new JButton("Ok");
        cancel = new JButton("Cancel");

        ok.setPreferredSize(new Dimension(100, 25));
        cancel.setPreferredSize(new Dimension(100, 25));

        contentPane = getContentPane();

        contentPane.setLayout(new FlowLayout());

        fontTitle = new Font("Comic Sans Ms", Font.BOLD + Font.ITALIC, 12);
        panel.setBorder(BorderFactory.createLineBorder(Color.blue));

        panel.add(ok);
        panel.add(cancel);

        contentPane.add(panel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

class BorderDemo {
    public static void main(String args[]) {
        MyBorderFrame frame = new MyBorderFrame();
        frame.setSize(400, 100);
        frame.setVisible(true);
    }
}

Output :

Line Border :

Swing BorderFactory Line

Bevel Border :

panel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));

 

Swing BorderFactory Bevel

Etched Border :

panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(EtchedBorder.RAISED),
"Titled Border", TitledBorder.RIGHT, TitledBorder.TOP,
fontTitle, Color.red));

Swing BorderFactory Etched

Bevel and Etched Border :

panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
"Font Names", TitledBorder.RIGHT, TitledBorder.TOP, fontTitle,
Color.red));

Swing BorderFactory Bevel Etched

Happy Learning 🙂