Ravichandra Namburi Ravichandra Namburi - 1 year ago 71
Java Question

How to override color and font for a JLabel?

I need to create a class

that would have customized color and font.

I need all
to have the following effect

JLabelTest.setFont(new Font("Comic Sans MS", Font.BOLD, 20));

This is what I tried

public class XLabel extends JLabel {

public void setFont(Font f)
super.setFont(new Font("Comic Sans MS", Font.BOLD, 20));

public void setForeground(Color fg)

However, when I try to use it
XLabel test= new XLabel("test")
does not compile , because constructor
XLabel (String )
is undefined. But it extends
, so it should inherit all it's constructors . Why doesn't it ? How to set customized color and font ?

Answer Source

You don't need to override those methods. JLabel is an abstract class, so XLabel automatically inherits those methods. Remove those methods from the XLabel class and try specifying the foreground and font in the constructor.

public class XLabel extends JLabel {

public XLabel(String text) {
    this.setFont(new Font("Comic Sans MS", Font.BOLD, 20));

Then, whenever you create an instance of XLabel, the methods setForeground() and setFont() are automatically called. This makes any instance of XLabel have the color pink, and the font Comic Sans.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download