0

如何实时转换输入字段中写入的内容。

例如。我想将 int 转换为二进制。我应该使用什么动作侦听器,以便在我键入要转换的 int 时,答案已经显示。

4

1 回答 1

1

Extend the KeyAdaptor class and implement the KeyPressed method.
Like so:

class KeyPressListener extends KeyAdapter {

  @Override
  public void keyPressed(KeyEvent event) { 
    char ch = event.getKeyChar();

    if (ch >= 'a' && ch <= 'z') { 
      System.out.println(event.getKeyChar());
    }
  }
}

Here's the Java info on KeyAdapter: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyAdapter.html

If you want to capture all changes, then you add an Action to your editbox, like so:

public class MyClass implements Action { 

  ....
  textField.addActionListener(this);

  public void actionPerformed(ActionEvent evt) { 
    String text = textField.getText();
    .. do stuff with text.
  }

And here are the related Java docs:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionEvent.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/Action.html

于 2013-10-10T03:21:53.107 回答