Link to home
Start Free TrialLog in
Avatar of JDay
JDay

asked on

Need keys to perform action, and not edit text in a JTextField

I have a JTextField with several components. When the JTextField has focus I would like to use the <->, <+>, <Ins>, <Del>, keys as hot keys on buttons. I have the funcionality correct for the hotkeys, however when I type the <->, <+>, <Ins>, <Del> it is adds or deletes the JTextField text first. I would like to disable the <->, <+>, <Ins>, <Del> keys from changing the text in the JTextField and only use them for the keyListner to perform the methods of the buttons.

I feel like there should be an included method to do this.
I could change the JTextField to different type text object if I can find something that works better.
I would appreciate any help.
Avatar of kotan
kotan
Flag of Malaysia image

Add KeyListener to your JTextField. Then from the KeyEvent parameter, you can get the key pressed through getKeyChar() or getKeyCode() to compare it.

YourJTextField.addKeyListener(new java.awt.event.KeyAdapter()
{
     public void keyPressed(java.awt.event.KeyEvent evt)
     {
          // See Blow
             if (evt.getKeyChar() == '-')
               // do your thing.
          else if (evt.getKeyChar() == '+')
               // do your thing.
          else if (evt.getKeyCode() == KeyEvent.VK_INSERT)
               // do your thing.
          else if (evt.getKeyCode() == KeyEvent.VK_DELETE)
               // do your thing.
        }
});


Avatar of JDay
JDay

ASKER

I have already tried this solution.

The textfield should not be edited when the keys are pressed. For example, the minus should not be added to the textfield before calling the associated method. The textfield is still being edited.

JDay
ASKER CERTIFIED SOLUTION
Avatar of kotan
kotan
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JDay

ASKER

Thank you the evt.consume() did the trick!
Thanks,
Jamie