如何创建 JTree ExpansionListener

How to create a JTree ExpansionListener

我在创建 TreeExpansionListener 时遇到问题。我认为它可以像 TreeSelectionListener 一样简单。不幸的是我找不到正确的界面。

这是我的听众:

private TreeExpansionListener createExpansionListener() {
    return (TreeExpansionEvent event) -> {
        TreePath path = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("Expanded: " + data);
    };
}

我收到的错误是"incompatible types: TreeExpansionListener is not a functional interface. multiple non-overriding abstract methods found in TreeExpansionListener"

与我的TreeSelectionListener相比: 私有 TreeSelectionListener createSelectionListener() { return (TreeSelectionEvent e) -> {

        node = (DefaultMutableTreeNode) template_tree.getLastSelectedPathComponent();
        if ((node == null){ 
            return;
        } else {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)   path.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("Expanded: " + data);
        };
}

我是不是做错了?还是我遗漏了一些明显的东西?

您不能在非功能性接口上使用 lambda 表达式。函数式接口只有一个抽象方法。

TreeExpansionListener

TreeSelectionListener


private TreeExpansionListener createExpansionListener() {
   return new TreeExpansionListener(){
   // implement methods and do stuff...
   }
}