[英]Class constructor calling another
I'd like to have 2 constructor with one that calls the other. 我想有2个构造函数,其中一个调用另一个。
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". 我需要获得preferredSize,但是NetBeans说了类似“在调用超类型构造函数之前无法引用此内容”之类的内容。
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. 我的朋友告诉我将getPreferredSize放入变量中,但是没有用。
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: 可以使用
Builder
模式来解决此问题:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.