Java Swing: How to get TextArea value including the char just typed?

前端 未结 3 1718
星月不相逢
星月不相逢 2021-01-27 02:05

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

If I do it in the even listener, textarea.getText() return

相关标签:
3条回答
  • 2021-01-27 02:37

    You need to use a DocumentListener and wirte your code in one of the xxxupdate() methods.

    0 讨论(0)
  • 2021-01-27 02:54

    Have you tried registering a KeyListener with a custom implementation of keyReleased(KeyEvent e) ?

    check the api here: KeyListener

    sun's tutorial with examples: How to write a Key Listener

    0 讨论(0)
  • 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);
    

    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).

    0 讨论(0)
提交回复
热议问题