Ravichandra Namburi Ravichandra Namburi - 5 months ago 8
Java Question

How to override color and font for a JLabel?

I need to create a class

XLabel
that would have customized color and font.

I need all
JLabels
to have the following effect

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


This is what I tried

public class XLabel extends JLabel {

@Override
public void setFont(Font f)
{
super.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
repaint();
}

@Override
public void setForeground(Color fg)
{
super.setForeground(Color.PINK);
repaint();
}
}


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

Answer

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) {
    super(text);
    this.setForeground(Color.BLACK);
    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.