Add a Custom Label
Learn how to make a label that can be used by every program to preserve consistency.
We'll cover the following
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.
- Extend the
TitleLabel
class withJLabel
and containing no stub code. - Add a private static final long instance variable called
serialVersionUID
and set it to1L
. - Add a
TitleLabel
constructor with a string parameter calledtitle
. In the constructor:- Create a new
Font
object calledfont
, from the Serif family, bold, and size32
. Use Font’sSERIF
andBOLD
variables. - Set the font to font. Use JLabel’s
setFont()
method. - Set the background to black. Use JLabel’s
setBackground()
method and Color’sBLACK
variable. - Set the foreground to white using JLabel’s
setForeground()
method and Color’sWHITE
variable. - Make the
TitleLabel
opaque using JLabel’ssetOpaque()
method. - Center the text horizontally. Use JLabel’s
setHorizontalAlignment()
method and JLabel’sCENTER
variable. - Set the
TitleLabel
's text to title using JLabel’ssetText()
method.
- Create a new
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.