【发布时间】:2010-04-27 01:24:53
【问题描述】:
在我看来,树选择事件应该在焦点事件之后发生,但事实并非如此。假设您有一个 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);
}
}
【问题讨论】:
-
你永远不应该根据事件的顺序编写代码。
-
您应该在事件调度线程上构建 GUI:java.sun.com/docs/books/tutorial/uiswing/concurrency/…
-
我同意你的观点:如果在树选择事件之前触发焦点事件会更合乎逻辑。
-
所以我不应该假设 windowClosing 事件将在 windowClosed 事件之前发生?有趣...
-
已经有一段时间了,但无法抗拒:我不应该假设 windowClosing 事件将在 windowClosed 事件之前 - 多么愚蠢的评论,除非假设你没有't read the doc ;-)