【发布时间】:2019-02-08 04:29:35
【问题描述】:
我正在尝试创建几个最终可以添加到 JToolBar 的自定义按钮。我有一个从 JButton 扩展而来的类,看起来像这样:
public class CustomToolbarJButton extends JButton {
public void setCustomProperties() {
this.putClientProperty("Property1", "Value1");
}
// Some other CustomToolbarJButton specific code here.
}
我有另一个类,CustomToolbarJToggleButton,它从 JToggleButton 扩展而来,并具有与 setCustomProperties() 方法完全相同的代码。
我的问题是,有什么方法可以创建一个抽象父类,这两个类最终可以继承自,这样我就可以将 setCustomProperties() 方法拉到该父类。
编辑
我想为我最终想要做的事情添加一些背景信息。
我想要一个这样的父类:
public abstract class CustomToolbarButton extends <some-class> {
public void setCustomProperties() {
this.putClientProperty("Property1", "Value1");
}
}
public class CustomToolbarJButton extends CustomToolbarButton {
// Some other CustomToolbarJButton specific code here.
}
public class CustomToolbarJToggleButton extends CustomToolbarButton {
// Some other CustomToolbarJToggleButton specific code here.
}
并最终将按钮添加到工具栏,我想创建一个类似的方法:
public void addCustomButtonToToolbar(boolean standardButtonOrToggleButton, String text) {
CustomToolbarButton customToolbarButton = standardButtonOrToggleButton ? new CustomToolbarJButton(text) : new CustomToolbarJToggleButton(text);
customToolbarButton.setCustomProperties();
this.toolbar.add(customToolbarButton); // toolbar is a JToolBar. I wanted to add the customToolbarButton directly to it, just like a standard JComponent.
}
这样的事情可能吗?
【问题讨论】:
-
由于java不支持多重继承,我建议你使用带有
setCustomProperties()方法的接口,或者你必须在CustomToolbarJButton类和JButton之间有抽象类类 -
如果
CustomToolbarJButton和CustomToolbarJToggleButton具有完全相同的属性,即相同的名称和相同的值,请编写一个单独的方法来接受任一实例并设置属性。可能是单独类中的静态方法。
标签: java inheritance