Add a Custom Label

Learn how to make a label that can be used by every program to preserve consistency.

We will make all the games in this course look like they are part of a collection by making each game’s title look the same. Instead of writing the same code in every program, we will create a custom label every program can use.

Creating a TitleLabel class

Start writing the TitleLabel class. We have already provided you with a java project called mycomponents containing the TitleLabel class.

  1. Extend the TitleLabel class with JLabel and containing no stub code.
  2. Add a private static final long instance variable called serialVersionUID and set it to 1L.
  3. Add a TitleLabel constructor with a string parameter called title. In the constructor:
    • Create a new Font object called font, from the Serif family, bold, and size 32. Use Font’s SERIF and BOLD variables.
    • Set the font to font. Use JLabel’s setFont() method.
    • Set the background to black. Use JLabel’s setBackground() method and Color’s BLACK variable.
    • Set the foreground to white using JLabel’s setForeground() method and Color’s WHITE variable.
    • Make the TitleLabel opaque using JLabel’s setOpaque() method.
    • Center the text horizontally. Use JLabel’s setHorizontalAlignment() method and JLabel’s CENTER variable.
    • Set the TitleLabel's text to title using JLabel’s setText() method.
package mycomponents;
 
import java.awt.Color;
import java.awt.Font;
 
import javax.swing.JLabel;
 
public class TitleLabel extends JLabel {
  private static final long serialVersionUID = 1L;
 
  ___________ TitleLabel(______________) {
    __________ font = ________________;
    setFont(_______);
    setBackground(__________);
    setForeground(________);
    setOpaque(______);
    setHorizontalAlignment(__________);
    setText(_______);
  }
}

Get hands-on with 1200+ tech skills courses.