我有这段代码,其中 aJTextArea
添加到 aJFrame
中。每当用户按下↑</kbd> key the content of the JTextArea
should be selected.
这是代码
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class SelectionTest extends KeyAdapter
{
final JTextArea jTextArea;
public static void main(String[] args)
{
new SelectionTest();
}
SelectionTest()
{
JFrame jFrame=new JFrame();
jFrame.setLocationRelativeTo(null);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jTextArea = new JTextArea("Test 1-2-3");
jTextArea.addKeyListener(this);
jFrame.add(jTextArea);
jFrame.pack();
jFrame.setVisible(true);
}
@Override
public void keyPressed(KeyEvent e)
{
if( e.getKeyCode() != KeyEvent.VK_UP ) return;
jTextArea.selectAll();
}
}
但是我观察到按下时没有选择任何内容↑</kbd> key,
instead if I slightly change the method keyPressed
to the following, it works.
@Override
public void keyPressed(KeyEvent e)
{
if( e.getKeyCode() != KeyEvent.VK_UP ) return;
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
jTextArea.selectAll();
}
});
}
我想知道这种行为的原因。是线程问题吗?