gpt4 book ai didi

java - 修改 JTree 中的焦点遍历

转载 作者:行者123 更新时间:2023-12-01 19:00:27 24 4
gpt4 key购买 nike

我有一个工作正常的 JTree,混合了叶节点和非叶节点。当我给予树根焦点时,向下箭头和向上箭头键会执行明显的操作。我想要做的小改变是使用向上/向下箭头使焦点转到下一个非叶节点(即跳过叶节点)。我可以(我认为)通过让持有树的 JPanel 响应向上和向下箭头键、检查节点并相应移动来了解如何做到这一点,但这似乎是在重新发明焦点子系统。

是否有更简单的方法,也许对树采用新的焦点遍历策略?

谢谢

最佳答案

面板与树内部导航没有任何关系,也不与焦点相关。这一切都是通过树的 actionMap 中的 keyBindings 来处理的。因此,解决方案是用自定义操作替换默认导航操作。下面的代码片段通过委托(delegate)给默认值来完成此操作:

    final JXTree tree = new JXTree();
tree.expandAll();
final Action delegate = tree.getActionMap().get("selectNext");
Action action = new AbstractAction("navigateNonLeaf") {

@Override
public void actionPerformed(ActionEvent e) {
boolean searching = true;
while (searching) {
TreePath old = tree.getLeadSelectionPath();
delegate.actionPerformed(e);
TreePath path = tree.getLeadSelectionPath();
// nothing happened, back off
if (areSame(old, path)) break;
Object last = path.getLastPathComponent();
if (!tree.getModel().isLeaf(last)) {
searching = false;
}
}
}

// TBD: implement "end of tree"
private boolean areSame(TreePath old, TreePath path) {
return path.equals(old);
}
};
tree.getActionMap().put("selectNext", action);

关于java - 修改 JTree 中的焦点遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444291/

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