Java Source Code: Create Different Borders of a Label

Java - Set Different Borders of a Label

This is a Java source code for a simple graphical application that demonstrates how to use various types of borders in Swing, a Java GUI toolkit. The program defines a class BorderDemo that extends JApplet, a Swing component used for embedding a Java application in a web page or other container.

In this java code, a method make(Border border, String command) is defined to create a new JLabel with the specified Border object and text label. This method is called multiple time, each time with a different type of border and a label describing the border. The borders are created using the BorderFactory class, which provides convenient methods for creating various types of borders in Swing.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;

public class BorderDemo extends JApplet {

   public void init() {
      setBackground(Color.lightGray);
      getContentPane().setBackground( Color.lightGray );
      getContentPane().setLayout( new GridLayout(0,1,7,7) );
      make(BorderFactory.createLineBorder(Color.red,2),
          "BorderFactory.createLineBorder(Color.red,2)");
      make(BorderFactory.createMatteBorder(2,2,5,5,Color.red),
          "BorderFactory.createMatteBorder(2,2,5,5,Color.red)");
      make(BorderFactory.createEtchedBorder(),
          "BorderFactory.createEtchedBorder()");
      make(BorderFactory.createRaisedBevelBorder(),
          "BorderFactory.createRaisedBevelBorder()");
      make(BorderFactory.createLoweredBevelBorder(),
          "BorderFactory.createLoweredBevelBorder()");
      make(BorderFactory.createTitledBorder("Title Goes Here"),
          "BorderFactory.createTitledBorder(\"Title Goes Here\")");
   }

   void make(Border border, String command) {
         // Make a lable showing the string and with the specified border.
         // The label will be opaque and will have a light gray background.
         // The label is added to the applet's content pane.
      JLabel label = new JLabel(command, JLabel.CENTER);
      label.setBackground(Color.lightGray);
      label.setOpaque(true);
      label.setBorder(border);
      getContentPane().add(label);
   }

   public Insets getInsets() {
        // Leave a border around the applet where the background
        // color will show through.
      return new Insets(7,7,7,7);
   }

} // end class JApplet
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post