我有两种类型的编辑器。一个是 JTextArea
的子类一个是 JTable
的子类( JTextArea
和 JTable
都是 JComponent
的子类)。我想要我的两个类(class),TextAreaEditor
和 TableEditor
实现接口(interface) Editor
,它只有方法 public String getText()
.
我希望客户端代码简单地使用 Editor
界面。问题是,我所有的 Editor
JComponent
的使用方法, 比如 setEnabled(bool)
.由于我的编辑器是一个接口(interface),我不能让它扩展 JComponent,所以在调用这些方法时我必须使用实现而不是接口(interface)。所以我想不用接口(interface),我可以简单地制作 Editor
JComponent
的子类并让我的类(class)扩展它。问题是类 TextAreaEditor
已经扩展了一些类,如 JTextArea
,所以我不能让他们扩展另一个类。
有什么方法可以确保我的 Editor
类是一个 JComponent,我的具体编辑器类是 Editor
JComponent
的小类和子类?
最佳答案
如果您在编辑器界面的子类中公开您关心的 JComponent 方法,它们将由您的类“追溯”实现。
下面是一些代码来演示这个想法:
interface Editor {
String getText();
}
interface SwingEditor extends Editor {
void setEnabled(bool); // has to match *exactly* the signature from JComponent
}
class TableEditor extends JTable implements SwingEditor {
// implement your getText(), and anything else you need
// no need to implement setEnabled, as it is provided by JTable
}
SwingEditor te = new TableEditor();
te.setEnabled(true); // will call JComponent's method
我假设您在这里确实需要继承,通常组合对于 Swing UI 代码来说通常是更好的选择。
关于java - 我如何确保接口(interface)实现扩展特定类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11605996/