代码之家  ›  专栏  ›  技术社区  ›  M.E.

在JavaSwing中扩展JLabp以使用给定的字体(扩展类中的超级用法)

  •  0
  • M.E.  · 技术社区  · 6 年前

    我正在尝试创建一个新类 JXLabel 继承的 JLabel . 不同的是,这个扩展类将为标签分配一个默认字体。

    如果我尝试这个:

    public class JXLabel extends JLabel {
    
        Font f = new Font("Segoe UI", Font.PLAIN, 6);
    
        public JXLabel() {    
            super();
            this.setFont(f);
        }  
    
        public JXLabel(Icon icon) {
            super(icon);
            this.setFont(f);
        }  
    
        public JXLabel(Icon icon, int horizontalAlignment) {
            super(icon, horizontalAlignment);
            this.setFont(f);
        }  
    
        public JXLabel(String text) {
            super(text);
            this.setFont(f);
        }  
    
        public JXLabel(String text, Icon icon, int horizontalAlignment) {
            super(text, icon, horizontalAlignment);
            this.setFont(f);
        }  
    
        public JXLabel(String text, int horizontalAlignment) {
            super(text, horizontalAlignment);
            this.setFont(f);
        }  
    }
    

    我希望新标签创建为 JXLAP 有这个默认字体,但没有。

    如果我创建一个常规的jLabel并执行以下操作:

    myLabel.setFont(new Font("Segoe UI", Font.PLAIN, 6));
    

    它起作用了。关于扩展类中的错误有什么提示吗?谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andrew Thompson    6 年前

    下面是上述代码的mcve,测试一种断言,即它以某种方式工作,而另一种方式不工作。在这里,它通过设置标准的字体来工作。 JLabel 或使用 JXLabel .

    看看你能不能:

    1. 在您的机器上确认结果
    2. 如果它按预期工作,请跟踪原始代码中的差异。

    import java.awt.*;
    import javax.swing.*;
    
    public class JXLabelTest {
    
        public static void main(String[] args) {
            Runnable r = () -> {
                String s = "The quick brown fox jumps over the lazy dog";
                JLabel myLabel = new JLabel(s);
                myLabel.setFont(new Font("Segoe UI", Font.PLAIN, 6));
                JOptionPane.showMessageDialog(null, myLabel);
                JOptionPane.showMessageDialog(null, new JXLabel(s));
            };
            SwingUtilities.invokeLater(r);
        }
    }
    
    class JXLabel extends JLabel {
    
        Font f = new Font("Segoe UI", Font.PLAIN, 6);
    
        public JXLabel() {    
            super();
            this.setFont(f);
        }  
    
        public JXLabel(Icon icon) {
            super(icon);
            this.setFont(f);
        }  
    
        public JXLabel(Icon icon, int horizontalAlignment) {
            super(icon, horizontalAlignment);
            this.setFont(f);
        }  
    
        public JXLabel(String text) {
            super(text);
            this.setFont(f);
        }  
    
        public JXLabel(String text, Icon icon, int horizontalAlignment) {
            super(text, icon, horizontalAlignment);
            this.setFont(f);
        }  
    
        public JXLabel(String text, int horizontalAlignment) {
            super(text, horizontalAlignment);
            this.setFont(f);
        }  
    }