CompoundBorder in Java Swing

In Java Swing, a CompoundBorder is a class that allows us to combine two different Border objects into a single border. This is useful when we want to apply multiple borders to a component, such as a panel or a button.

We can create a CompoundBorder using the BorderFactory.createCompoundBorder() method, which takes two Border objects as arguments. The first argument is the outer border, and the second argument is the inner border. The resulting CompoundBorder will have the appearance of the outer border, with the inner border inset by the outer border’s thickness.

Following is an example that demonstrates how to use CompoundBorder to apply two borders to a JPanel:

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;

public class CompoundBorderDemo extends JFrame {
    
    public CompoundBorderDemo() {
    	setLayout(new BorderLayout());
    	
        setTitle("CompoundBorder Demo");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.BLUE, 5),
            BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.YELLOW, Color.LIGHT_GRAY)
        ));
        add(panel, BorderLayout.NORTH);
        
        JLabel label = new JLabel("Hello, World!");
        label.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(label);
        
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new CompoundBorderDemo();
    }

}

In this example, we create a JPanel and set its border using BorderFactory.createCompoundBorder(). We pass in two Border objects: a blue line border with a thickness of 5 pixels as the outer border, and an Etched border with a type RAISED, highlighting color yellow and Light Grays as shadows for the inner border. The resulting border is a blue border with yellow and light gray shadows around the panel.

Output:

CompoundBorder in Java Swing ComoundBorder demo

You can experiment with different combinations of borders to achieve different effects using CompoundBorder.

Reference: https://docs.oracle.com/javase/tutorial/uiswing/components/border.html

Sharing Is Caring: