gpt4 book ai didi

java - 我如何确保接口(interface)实现扩展特定类?

转载 作者:搜寻专家 更新时间:2023-11-01 01:28:05 24 4
gpt4 key购买 nike

我有两种类型的编辑器。一个是 JTextArea 的子类一个是 JTable 的子类( JTextAreaJTable 都是 JComponent 的子类)。我想要我的两个类(class),TextAreaEditorTableEditor实现接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com