How do I create Border for swing component?

This example shows how we can create border for swing components. In the
example below we set border of a JPanel component. Some border
implementation that we use below including LineBorder,
BevelBorder, EtchedBorder and MatteBorder.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;

public class BorderDemo extends JFrame {

    public BorderDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(15, 15));

        JPanel top = new JPanel();
        top.setBorder(new LineBorder(Color.RED, 1, true));

        JPanel bottom = new JPanel();
        bottom.setBorder(new BevelBorder(BevelBorder.LOWERED));

        JPanel left = new JPanel();
        left.setBorder(new EtchedBorder(EtchedBorder.RAISED));

        JPanel right = new JPanel();
        right.setBorder(new MatteBorder(5, 5, 5, 5, Color.BLUE));

        JPanel center = new JPanel();
        center.setBorder(new BevelBorder(BevelBorder.RAISED));

        getContentPane().add(top, BorderLayout.NORTH);
        getContentPane().add(bottom, BorderLayout.SOUTH);
        getContentPane().add(left, BorderLayout.WEST);
        getContentPane().add(right, BorderLayout.EAST);
        getContentPane().add(center, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new BorderDemo().setVisible(true);
            }
        });
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply