我用 Java 实现了以下代码。
public class FadeLabel extends javax.swing.JLabel {
private Timer onTimer;
public FadeLabel() {
init();
}
private void init(){
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
onTimer = new Timer(100, (ActionEvent e) -> {
// animation code
});
}
@Override
public void setText(String text) {
onTimer.start();
super.setText(text);
}
}
当我创建此类的对象时,它在 setText()
方法中给出了一个 NullPointerException
,onTimer.start()
.
我想知道为什么会出现这个异常..?
ps: 我知道什么是NullPointerException
。我想知道这里是怎么生成的..
这就是我实例化的方式。
notificationLabel = new FadeLabel();
最佳答案
查看 source code对于 JLabel
public JLabel() {
this("", null, LEADING);
}
public JLabel(String text, Icon icon, int horizontalAlignment) {
setText(text);
setIcon(icon);
setHorizontalAlignment(horizontalAlignment);
updateUI();
setAlignmentX(LEFT_ALIGNMENT);
}
因此我们可以看到无参数构造函数调用了另一个,然后调用了 setText
。但是此时您的 init
方法还没有运行,所以 onTimer
仍然是 NULL
。
关于java - 重写 JLabel 中的 setText() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46704244/