如何编写树选择监听器

原文: https://docs.oracle.com/javase/tutorial/uiswing/events/treeselectionlistener.html

要检测用户何时选择中的节点,您需要注册树选择监听器。这是一个例子,取自响应节点选择中讨论的TreeDemo示例,检测树中的节点选择,该树中一次最多只能选择一个节点:

  1. tree.addTreeSelectionListener(new TreeSelectionListener() {
  2. public void valueChanged(TreeSelectionEvent e) {
  3. DefaultMutableTreeNode node = (DefaultMutableTreeNode)
  4. tree.getLastSelectedPathComponent();
  5. /* if nothing is selected */
  6. if (node == null) return;
  7. /* retrieve the node that was selected */
  8. Object nodeInfo = node.getUserObject();
  9. ...
  10. /* React to the node selection. */
  11. ...
  12. }
  13. });

要指定树应支持单选,程序将使用以下代码:

  1. tree.getSelectionModel().setSelectionMode
  2. (TreeSelectionModel.SINGLE_TREE_SELECTION);

TreeSelectionModel接口为选择模式定义了三个值:

DISCONTIGUOUS_TREE_SELECTION

This is the default mode for the default tree selection model. With this mode, any combination of nodes can be selected.

SINGLE_TREE_SELECTION

This is the mode used by the preceding example. At most one node can be selected at a time.

CONTIGUOUS_TREE_SELECTION

With this mode, only nodes in adjoining rows can be selected.

因为TreeSelectionListener只有一个方法,所以它没有相应的适配器类。

方法 目的
valueChanged(TreeSelectionEvent) 每当选择改变时调用。
方法 目的
对象 getSource()

java.util.EventObject中的)_ | 返回触发事件的对象。 | | TreePath getNewLeadSelectionPath() | 返回当前的潜在客户路径。 | | TreePath getOldLeadSelectionPath() | 返回先前引导路径的路径。 | | TreePath getPath() | 返回第一个路径元素。 | | TreePath [] getPaths() | 返回已从选择中添加或删除的路径。 | | boolean isAddedPath() | 如果已将第一个路径元素添加到选择中,则返回 true。如果已从选择中删除第一个路径,则返回 false。 | | boolean isAddedPath(int) | 如果索引指定的路径已添加到选择中,则返回 true。 | | boolean isAddedPath(TreePath) | 如果指定的路径已添加到选择中,则返回 true。 | | Object getLastSelectedPathComponent() | 返回当前选择的第一个节点中的最后一个路径组件。 | | TreePath getLeadSelectionPath()JTree中的)_ | 返回当前的潜在客户路径。 |

下表列出了使用树选择监听器的示例。

在哪里描述 笔记
TreeDemo
如何使用树木 树监听器通过显示相应的 HTML 文档来响应节点单击。