Search code examples
javaswinginheritancejbuttonmethod-hiding

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

Solution

  • 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.