0

how to convert what is written in input field in real time.

for example. I want to convert an int to binary. what action listener should I use so that while I type the int to be converted the answer is already displayed.

user2768260
  • 29
  • 3
  • 6
  • What have you done? What ActionListener you say? My guess would be probably one attached to a button on a GUI... – Tdorno Oct 10 '13 at 03:20
  • You are looking for a key listener. Look at http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html – David says Reinstate Monica Oct 10 '13 at 03:20
  • or should I use keylistener? how do I use it? – user2768260 Oct 10 '13 at 03:25
  • `KeyListener` is not a good choice for this. So long as you don't actually want to change what's going into the field, `DocumentListener` is a better choice, as it will be notified when the user types something, you use `setText` or the user pastes something into the field. `KeyListener` will work only for the first option. – MadProgrammer Oct 10 '13 at 03:27

1 Answers1

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

Johan
  • 74,508
  • 24
  • 191
  • 319
  • This won't work for a number of reasons, but mostly, if I paste content into the field, it won't be registered by the key listener at all... – MadProgrammer Oct 10 '13 at 03:25