1

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 ?

  • Possible duplicate of [Java Constructor Inheritance](http://stackoverflow.com/questions/1644317/java-constructor-inheritance) – VGR Jun 26 '16 at 12:42

1 Answers1

1

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.

Jake Miller
  • 2,432
  • 2
  • 24
  • 39
  • This is exactly what I do. But this results in duplicate code. when I have hundreds of those `JLabel` elements and `setFont` and `setForeground` for each. – Ravichandra Namburi Jun 26 '16 at 02:54
  • Ahh. You didn't specify that you'd need multiple JLabels with these exact properties in the question. You'd simply create a constructor for `XLabel` which sets the font and foreground. I'll update my answer with the correct code. – Jake Miller Jun 26 '16 at 03:06
  • Thank you for the update. I also tried that. This constructor is only good for when we instantiate without any arguments. It won't work when I use `XLabel test = new XLabel("test")` because constructor `XLabel (String ) is undefined` – Ravichandra Namburi Jun 26 '16 at 03:09
  • Thank you . i was messing for hours with the `paintComponent` and other methods – Ravichandra Namburi Jun 26 '16 at 03:13
  • No problem! Also, the better way to do it is to use `super(text)` now that I think about it. Edited it again. But either way works. – Jake Miller Jun 26 '16 at 03:14