this()
& super()
can only be called in the first line of the constructor.
This means that you can either call this()
or super()
because only one of these can take the first line.
If you don't mention this()
or super()
the compiler will call super()
(with no arguments).
I would solve your problem by doing something like this:
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()
}
UPDATE:
Notice the code you provided:
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();
}
}
Notice the super()
in CustomButton()
. So in this case, it would mean that:
public CustomButton(ImageIcon img){
super(img);
this();
}
super()
is being called twice, once by CustomButton()
and once by CustomButton(ImageIcon img)
which could lead to unexpected results depending on the constructors of JButton
It is for this reason, that Java expects this()
or super()
to take the first line.