Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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);
    }
}
like image 650
jhlu87 Avatar asked Dec 28 '22 19:12

jhlu87


2 Answers

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.

like image 65
aioobe Avatar answered Feb 08 '23 22:02

aioobe


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)

like image 40
Heisenbug Avatar answered Feb 08 '23 23:02

Heisenbug