this()&super()只能在构造函数的第一行调用。
这意味着您可以调用this(),或者super()因为只有其中一个可以占用第一行。
如果您不提及this()或super()编译器将调用super()(不带参数)。
我会通过执行以下操作来解决您的问题:
private void init()
{
try {
URL inp = CustomButton.class.getResource("/icons/noa_en/buttonBackground.png");
background = ImageIO.read(inp);
} catch (IOException e) {
e.printStackTrace();
}
}
public CustomButton()
{
init();
}
public CustomButton(ImageIcon img){
super(img);
init()
}
更新:
注意您提供的代码:
public CustomButton(){
super(); // This gets automatically added to the constructor
try {
URL inp = CustomButton.class.getResource("/icons/noa_en/buttonBackground.png");
background = ImageIO.read(inp);
} catch (IOException e) {
e.printStackTrace();
}
}
注意super()in CustomButton()。所以在这种情况下,这意味着:
public CustomButton(ImageIcon img){
super(img);
this();
}
super()被调用两次,一次CustomButton()又一次,CustomButton(ImageIcon img)这可能会导致意外的结果,具体取决于JButton
正是出于这个原因,Java 期望this()或super()占据第一行。