Java:错误:在调用超类型构造函数之前无法引用此内容

问题描述 投票:0回答:1

我正在尝试向javax.swing.ImageIcon添加一个构造函数。它必须解析目录结构,以便能够像图像映射一样访问ImageIcon类。

我想做的是:

public class CPImageIcon extends ImageIcon {

    public CPImageIcon(String name) {

        super(this.getClass().getResource("/desktopapplication1/resources/" + name), "description");
    }

但这导致:

warning: [options] bootstrap class path not set in conjunction with -source 1.7
I:\DesktopApplication1\src\desktopapplication1\CPImageIcon.java:18: error: cannot reference this before supertype constructor has been called
        super(this.getClass().getResource("/desktopapplication1/resources/" + name),"");

如果我尝试替代其他构造函数,则可以使用。

java constructor imageicon
1个回答
0
投票

super构造函数必须是子类构造函数中的第一个调用。如果省略,它将自动调用默认构造函数super()this表示当前实例,不能在调用super之前调用。

您可以使用以下方法,有注释或无注释:

import javax.swing.*;

public class CPImageIcon extends ImageIcon {

    public CPImageIcon(String name) {
        super(CPImageIcon.class.getResource("/desktopapplication1/resources/" + name), "description");
//        super(Thread.currentThread().getContextClassLoader().getResource("/desktopapplication1/resources/" + name), "description");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.