JTextArea - 清除文本并将插入符号返回到起始区域

时间:2014-06-29 12:50:44

标签: java swing jtextarea keylistener

我有一个小但烦人的问题。我正在使用JTextArea来捕获带有KeyListener的输入 - 它只是在按下返回按钮后捕获输入。问题是,当我清除文本时,插入符号位于第二行,这令人恼火。

以下是代码:

@SuppressWarnings ("serial")
public class ProgramEditor extends JTextArea implements KeyListener {

    //FIELDS
    String command = "";

    //CONSTRUCTOR
    public ProgramEditor() {
        super();
        this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        this.setLineWrap(true);

        addKeyListener(this);

        this.requestFocus();
     }

    @Override
    public void keyPressed(KeyEvent e) {
         int i = e.getExtendedKeyCode();
         if (i == 10){
            command = this.getText();
            this.setText(null);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

使用键绑定进行Swing来处理事件。对于JTextArea,Enter键由键绑定处理,键绑定将换行符串插入文本区域。因此,此代码在您的keyPressed代码之后执行。

正确的解决方案是将Enter键的默认操作替换为您自己的自定义操作。阅读Key Bindings上Swing教程中的部分,了解更多信息和示例。

问题是为什么你在用户中使用JTextArea永远不能输入换行符?更简单的解决方案是使用JTextField。然后,您可以将ActionListener添加到文本字段以处理Enter键。

最后,最糟糕的解决方案是尝试处理keyReleased()方法。然后应该执行文本区域的回车键的默认操作。

答案 1 :(得分:0)

尝试使用JTextArea中的setCaretPosition(int)方法,特别是将keyPressed变为

@Override
public void keyPressed(KeyEvent e) {
    int i = e.getExtendedKeyCode();
if (i == 10){
    command = this.getText();
    this.setText(""); //I'd use "" over null; it just seems more proper to keep a string even if there's no difference
    this.setCaretPosition(0);
}
}

检查出来:http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition(int)

答案 2 :(得分:0)

尝试使用它:

this.setCaretPosition(0);