JButton的Java子类重写setEnabled方法问题
我有一个名为 ImageButton 的自定义按钮类,它扩展了 JButton。在其中我有一个我想要调用的 setEnabled 方法,而不是 JButton 的 setEnabled 方法。
我的代码如下。在我的另一个类中,我创建了一个 ImageButton 的新实例,但是当我尝试使用 setEnabled 方法时,它直接转到 JButton 的 setEnabled 方法。甚至在我运行代码之前,我的 IDE 就告诉我 ImageButton 的 setEnabled 方法从未被使用过。如果我将方法更改为“SetOn”,它就可以正常工作。那么为什么我不能使用与超类相同的名称呢?我认为如果同名,它应该隐藏超类方法吗?
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要更改
为
(通过使用
Boolean
而不是boolean
,您是在重载该方法,而不是覆盖它。)我鼓励您始终注释旨在覆盖另一个方法的方法与@Override。如果你在这种情况下这样做了,编译器会抱怨并说类似的话
You need to change
to
(By using
Boolean
instead ofboolean
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尝试在布尔值中不使用大写字母:布尔值和布尔值之间存在差异,因此签名不同:
带大写字母的布尔值是一个类。
布尔值是语言的原始类型。
(同样适用于 int 与 Integer、double 与 Double 等)
Try without the capital letter in Boolean: there is difference between Boolean and boolean, so the signature is different:
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)