开发者

Java subclass of JButton overriding setEnabled method problem

I have a custom button class called ImageButton that extends JButton. In it i have a setEnabled method that I want to be called rather than the JButton's setEnabled method.

My code is below. In my other class I create a new instance of ImageButton, but when I try to use the setEnabled method, it goes straight to the JButton's setEnabled method. Even before I run the code, my IDE is telling me that the ImageButton's setEnabled method is never used. If I change the method to "SetOn" it works fine. So why is it that I can't use the same name as that of the super class? I开发者_Go百科 thought it's supposed to hide the superclass method if it's the same name?

public class ImageButton extends JButton{

    public ImageButton(ImageIcon icon){
        setSize(icon.getImage().getWidth(null),icon.getImage().getHeight(null));
        setIcon(icon);
        setMargin(new Insets(0,0,0,0));
        setIconTextGap(0);
        setBorderPainted(true);
        setBackground(Color.black);
        setText(null);
    }

    public void setEnabled(Boolean b){
        if (b){
            setBackground(Color.black);
        } else {
            setBackground(Color.gray);
        }
        super.setEnabled(b);
    }
}


You need to change

public void setEnabled(Boolean b){

to

public void setEnabled(boolean b){
                       ^

(By using Boolean instead of boolean you're overloading the method instead of overriding it.)


I encourage you to always annotate methods intended to override another method with @Override. If you had done it in this case, the compiler would have complained and said something like

The method setEnabled(Boolean) of type ImageButton must override or implement a supertype method.


Try without the capital letter in Boolean: there is difference between Boolean and boolean, so the signature is different:

public void setEnabled(boolean b)

Boolean with the capital letter is a Class. boolean is a primitive type of the language. (The same is for int vs Integer, double vs Double, etc)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜