如何覆盖 JLabel 的颜色和字体?

How to override color and font for a JLabel?

我需要创建一个 class XLabel 来自定义颜色和字体。

我需要全部JLabels才能达到下面的效果

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

这是我试过的

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();
       }     
}

然而,当我尝试使用它时 XLabel test= new XLabel("test") 没有编译,因为构造函数 XLabel (String ) 是未定义的。但它扩展了 JLabel ,所以它应该继承它的所有构造函数。为什么不呢?如何设置自定义颜色和字体?

您不需要重写这些方法。 JLabel 是抽象的 class,因此 XLabel 自动继承了那些方法。从 XLabel class 中删除这些方法并尝试在构造函数中指定前景和字体。

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));
}

然后,每当您创建 XLabel 的实例时,都会自动调用方法 setForeground()setFont()。这使得 XLabel 的任何实例都具有粉红色和 Comic Sans 字体。