在我看来,树选择事件应该在焦点事件之后发生,但事实并非如此。假设您有一个 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);
}
}