java - JTree 事件似乎顺序错误

标签 java swing events jtree

在我看来,树选择事件应该发生在焦点事件之后,但事实并非如此。假设您有一个 JTree 和一个 JTextField,其中 JTextField 由在树中选择的内容填充。当用户更改文本字段时,如果焦点丢失,您可以从文本字段更新树。但是,在文本字段上失去焦点之前,树选择已更改。这是不正确的,对吧?有任何想法吗?这是一些示例代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Focus extends JFrame
{
 public static void main(String[] args)
 {
  Focus f = new Focus();
  f.setLocationRelativeTo(null);
  f.setVisible(true);
 }

 public Focus()
 {
  Container cp = getContentPane();
  cp.setLayout(new BorderLayout());

  final JTextArea ta = new JTextArea(5, 10);
  cp.add(new JScrollPane(ta), BorderLayout.SOUTH);

  JSplitPane sp = new JSplitPane();
  cp.add(sp, BorderLayout.CENTER);

  JTree t = new JTree();
  t.addTreeSelectionListener(new TreeSelectionListener()
  {
   public void valueChanged(TreeSelectionEvent tse)
   {
    ta.append("Tree Selection changed\n");
   }
  });
  t.addFocusListener(new FocusListener()
  {
   public void focusGained(FocusEvent fe)
   {
    ta.append("Tree focus gained\n");
   }
   public void focusLost(FocusEvent fe)
   {
    ta.append("Tree focus lost\n");
   }
  });

  sp.setLeftComponent(new JScrollPane(t));
  JTextField f = new JTextField(10);
  sp.setRightComponent(f);

  pack();

  f.addFocusListener(new FocusListener()
  {
   public void focusGained(FocusEvent fe)
   {
    ta.append("Text field focus gained\n");
   }
    public void focusLost(FocusEvent fe)
{
    ta.append("Text field focus lost\n");
   }
  });
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

最佳答案

让您的文本字段监听器调用 setSelectionPath()为与文本匹配的节点选择 TreePathDefaultMutableTreeNode的方法可以用来遍历树。我会在文本字段上使用 ActionListener,但是 FocusListener 应该可以工作——只是不要依赖于 TreeSelectionListener 的顺序事件到达。

这是在默认 JTree 中获取“pizza”节点的示例:

JTree tree = new JTree();
TreeNode node = (TreeNode) tree.getModel().getRoot();
node = node.getChildAt(2).getChildAt(1);
TreePath pizza = new TreePath(((DefaultMutableTreeNode) node).getPath());

关于java - JTree 事件似乎顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718167/

相关文章:

java - 如何以这种特殊方式在 Android 中使用微调器?

java - jpanel 无法很好地显示 jframe 设置为 gridbaglayout

javascript - scrollIntoView 影响我的监听器

c# - 需要解释使用 lambda 作为事件处理程序

c# - 触发事件时出现 NullReferenceException

java - Android SDK : System Setting

java - 通过用户点击进行碰撞检测

java - 如何在 Java 中禁用 kerberos 重播缓存?

java - 如何使用frame.add方法创建多个可见对象

java - 自定义 JOptionPane 图标