I'd like to have 2 constructor with one that calls the other.
example :
public class MyButton extends JButton {
private final ImageIcon neutralIcon;
private final ImageIcon pressedIcon;
private final ImageIcon rollOverIcon;
public MyButton(String n,
String p,
String r,
Dimension d)
{
neutralIcon = new ImageIcon(this.getClass().getResource(n));
pressedIcon = new ImageIcon(this.getClass().getResource(p));
rollOverIcon = new ImageIcon(this.getClass().getResource(r));
this.setIcon(neutralIcon);
this.setPressedIcon(pressedIcon);
this.setRolloverIcon(rollOverIcon);
this.setFocusPainted(false);
this.setContentAreaFilled(false);
this.setSize(d);
}
public MyButton(String n,
String p,
String r)
{
this(n,p,r,this.getPreferredSize()); // COMPILE ERROR
}
}
I need to get the preferredSize but NetBeans said something like "cannot reference this before supertype constuctor has been called".
I tried the 'super' thing but it still gives me error.
My friend told me to put the getPreferredSize into a variable but it didn't work.
Dimension d = this.getPreferredSize();
this(n,p,r,d); // COMPILE ERROR
Change the method call to a constant, so:
public MyButton(String n,
String p,
String r)
{
this(n,p,r,PREFERRED_SIZE);
}
The Builder
pattern could be used to work around this issue:
import java.awt.Dimension;
import javax.swing.JButton;
public class MyButton extends JButton {
private String n;
private String p;
private String r;
private Dimension d;
private MyButton(){
super();
}
static class MyButtonBuilder{
private String n;
private String p;
private String r;
private Dimension d;
public MyButtonBuilder(String n, String p, String r){
this.n = n;
this.p = p;
this.r = r;
}
public void setDimension(Dimension d){
this.d = d;
}
public MyButton build(){
MyButton myButton = new MyButton();
myButton.n = this.n;
myButton.p = this.p;
myButton.r = this.r;
myButton.d = (myButton.d == null) ? myButton.getPreferredSize():this.d;
return myButton;
}
}
public static void main(String[] args) {
MyButtonBuilder builder = new MyButton.MyButtonBuilder("1", "2","3");
MyButton myButton = builder.build();
}
}
try this
public MyClass(String n,
String p,
String r)
{
this(n,p,r,new Dimension(WIDTH, HEIGHT)); // COMPILE ERROR
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.