Java Swing:如何获取包括刚刚键入的char在内的TextArea值? [英] Java Swing: How to get TextArea value including the char just typed?

查看:53
本文介绍了Java Swing:如何获取包括刚刚键入的char在内的TextArea值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

键入键(包括此字符)后,获取TextArea值的最佳方法是什么?

What's the best way to get a value of a TextArea after a key is typed, including this character?

如果我在偶数侦听器中执行此操作,则 textarea.getText()返回的值将不包含最终的新字符.

If I do it in the even listener, textarea.getText() returns the value without the eventual new char.

基本上,我看到两种方法:

Basically I see two ways:

  1. 使用诸如invokeLater()之类的方法推迟处理.我希望没有线程的解决方案.

  1. postponing processing with something like invokeLater(). I would prefer a solution without threads.

根据字的位置确定将char放置在文本中的位置.

figuring out where to put the char into the text, based on the carret position.

还有其他更简单的吗?

谢谢.

这就是我所拥有的:

This is what I have:

JTextArea textarea = (JTextArea) evt.getComponent();
String texySource = textarea.getText();
char keyCode = evt.getKeyChar();
//if( Character.isLetterOrDigit( keyCode ) || Character.isSpaceChar( keyCode )  )
if( keyCode >= 0x20 || keyCode == 0x0A || keyCode == 0x0D  ){
    // TODO: The carret doesn't have to be at the end...
    //texySource += Character.toString( evt.getKeyChar() );

    String ch = Character.toString( evt.getKeyChar() );
    texySource = StringUtils.overlay(texySource, ch,
    textarea.getSelectionStart(),
    textarea.getSelectionStart()    );
}

推荐答案

您是否考虑过文档监听器?可能是因为打字事件而武装?

Have you considered a document listener? possibly armed by the typing event?

class TheListener implements DocumentListener, KeyListener {
  boolean armed;

  void keyPressed(KeyEvent ignore) { }
  void keyReleased(KeyEvent ignore) { }
  void keyTyped(KeyEvent e) {
    armed = true;
    SwingUtilities.invokeLater(new Runnable() { public void run() {
      armed = false;
    }
  }

  void deleteUpdate(DocumentEvent e) {
    changeUpdate(e);
  }
  void insertUpdate(DocumentEvent e) {
    changeUpdate(e);
  }
  void changedUpdate(DocumentEvent e) {
    if (armed) {
      String s = ((JTextComponent)e.getSource()).getText();
      //.... whatever you want to do now
    }
  }
}

//...
TheListener aListener = new TheListener();
textArea.addKeyListener(aListener);
textArea.getDocument().addDocumentListener(aListener);

理论是将文档更改侦听器设在键入的键上,然后添加EDT事件以撤消它.文档更改将先发生,然后再撤防.一旦准备好,您就可以假定任何文档更改在某种程度上都是由键键入事件引起的.(警告,我尚未编译此代码,YMMV).

The theory is to arm the document change listener on a key typed, then add an EDT event to disarm it. The document changes will occur first before disarmed. Once armed, you can assume that any document changes were caused in some part by the key typing event. (warning, I haven't compiled this code, YMMV).

这篇关于Java Swing:如何获取包括刚刚键入的char在内的TextArea值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆