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.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();
    }

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

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(WindowConstants.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);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.