类构造函数调用另一个

时间:2013-12-03 10:37:44

标签: java constructor jbutton

我希望有2个构造函数,其中一个构造函数可以调用另一个。

示例:

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
    }

}

我需要获取preferredSize,但NetBeans表示“在调用超类型构造函数之前无法引用此内容”。

我试过'超级'的东西,但它仍然给我错误。

我的朋友告诉我把getPreferredSize放到一个变量中,但它没有用。

Dimension d = this.getPreferredSize();
this(n,p,r,d); // COMPILE ERROR

3 个答案:

答案 0 :(得分:0)

将方法调用更改为常量,所以:

public MyButton(String n, 
                String p, 
                String r)
{   
    this(n,p,r,PREFERRED_SIZE);
}

答案 1 :(得分:0)

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();
    }
}

答案 2 :(得分:0)

试试这个

 public MyClass(String n, 
                    String p, 
                    String r)
    {   

        this(n,p,r,new Dimension(WIDTH, HEIGHT)); // COMPILE ERROR
    }