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

标签 java swing interface awt multiple-inheritance

我有两种类型的编辑器。一个是 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/

相关文章:

java - 尝试使用生产者和消费者模式打印斐波那契数列

java - 文本不会延迟更改

entity-framework - 通过接口(interface)属性 LINQ to Entities

java - 如何在 Java 中指定不区分大小写的搜索

java - 将整个 where 子句传递给 native spring jpa @Query

java - 如何解决 java.lang.ClassCastException 错误

java - JPanel 元素未出现

interface - FxCop + MVP : "Properties should not be write only"

c# - 坚持泛型和接口(interface)。需要基于代码的解决方案,可能需要重新设计接口(interface)

java - Java中有缓冲区填充接收方法吗?