4

Is there a simple way to cancel the user input in a JTextField when key Esc is pressed ?

I mean something different that a key listener and a data backup.

Thanks

Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68
user777466
  • 991
  • 2
  • 13
  • 21
  • 1
    everything you are recommended to do is _different_ from a KeyListener ;-) use keybindings - and add some logic that restores the possibly edited text in the field to the text at the last commit/load – kleopatra Aug 24 '11 at 10:11
  • I didn't knox the KeyBindings. It looks more efficient that keylistener, but not "that" different – user777466 Aug 24 '11 at 11:12
  • first look might not reveal all its power, it's definitely _much_ different ;-) – kleopatra Aug 24 '11 at 12:23

2 Answers2

0

Add a KeyListener to your JTextField:

JTextField field = new JTextField.addKeyListener(yourKeyListener);

where yourKeyListener could be:

public class YourKeyListener implements KeyListener{
    void keyPressed(KeyEvent e){
         Component source = e.getSource();
         if (source instanceof JTextField && e.getId() == KeyEvent.VK_ESCAPE ){

             JTextField f = (JTextField) source;
             f.setText("");

         }
    }
} 
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

CancelAction, discussed here and shown here, is an example that uses Action and a key binding.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    Yeah, but this Action is just resetting someting to "". I want to reset it to the value before first edit. – user777466 Aug 24 '11 at 11:13
  • You'll have to keep track of the unedited value, perhaps in your application's data model. – trashgod Aug 24 '11 at 11:20
  • 1
    @user777466 - looks like you either didn't completely read or didn't completely understand my comment, repeating myself: "add some logic that restores the possibly edited text in the field to the text of the last commit/load" – kleopatra Aug 24 '11 at 12:57