在我看来,树选择事件应该发生在焦点事件之后,但事实并非如此。假设您有一个 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()
为与文本匹配的节点选择 TreePath
。 DefaultMutableTreeNode
的方法可以用来遍历树。我会在文本字段上使用 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/