Using the BorderFactory in Swing

If you have lots of components with borders in your Swing GUI, you could create a Border instance for every component. The BorderFactory class provides a way to share border instances among different components. When using the class for the first time, it creates a number of static borders that it reuses and returns when you call one of the static create methods that the class exposes.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JLabel label1 = new JLabel("Label 1");
      label1.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      // reuse border
      JLabel label2 = new JLabel("Label 2");
      label2.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      getContentPane().add(label1);
      getContentPane().add(label2);
      
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   } 
}