gpt4 book ai didi

java - 如何实现监听器?

转载 作者:行者123 更新时间:2023-12-01 16:06:10 25 4
gpt4 key购买 nike

我有一些动态树。现在我需要实现一些功能,每次只需单击节点即可实现这些功能。 (我的意思是只需单击节点一次,“使其变为蓝色”)

**编辑2:**我使用beanTreeView和包openide

如何实现该 Action 的监听器?

编辑 - 添加伪代码

public class MyNode extends AbstractNode{ //openide package
private String name;

public MyNode(String nameOfNode){
super (new Children.LEAF);
name = nameOfNode;
}
....
....
}

public class IWantNameOfSelectedNode extends JPanel{
private JLabel jLnameOfNode;

public IWantNameOfSelectedNode(){
jLnameOfNode.setText("wiating for node selection");
}

现在,我需要将所选节点的名称放入 jLabel,并在每次选择的节点发生变化时更改它。

最佳答案

假设您使用的是 Swing JTree 类,您应该定义一个 TreeSelectionListener 并将其添加到底层 TreeModel 中。如果您希望使用 ActionListener,则需要编写一些适配器代码来将 TreeSelectionEvent 转换为 ActionEvent s(尽管这实际上毫无意义)。

示例

/**
* Adapter class responsible for translating TreeSelectionEvents into
* ActionEvents.
*/
public class TreeSelectionAdapter implements TreeSelectionListener {
private final AtomicInteger nextId = new AtomicInteger(0);
// Prefer CopyOnWriteArrayList to avoid ConcurrentModificationException if an
// ActionListener removes itself as a listener during notification.
private final CopyOnWriteArrayList<ActionListener> listeners;

public TreeSelectionAdapter() {
this.listeners = new CopyOnWriteArrayList<ActionListener();
}

public void addActionListener(ActionListener l) {
this.listeners.add(l);
}

public void removeActionListener(ActionListener l) {
this.listeners.remove(l);
}

public void valueChanged(TreeSelectionEvent evt) {
// Create new ActionEvent which corresponds to incoming TreeSelectionEvent
// and notify registered ActionListeners.
ActionEvent aEvt = new ActionEvent(evt.getSource(),
nextId.getAndIncrement(), "selectionChanged");

for (ActionListener listener : listeners) {
listener.actionPerformed(listener);
}
}
}

TreeNode rootNode = createTreeModel(); // Create custom model
JTree tree = new JTree(rootNode); // Install model into JTree.

// Add adapter listener to underlying selection model.
tree.getSelectionModel().addTreeSelectionListener(adapter);

// Register ActionListener with adapter listener.
adapter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.err.println("Selection has changed in some way!");
}
});

关于java - 如何实现监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2538054/

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