0

I'm working on a JTexfield which sets its own text to the name of the key pressed when it has the focus on the window. I've managed to let it have only a word with the code:

@Override
public void keyReleased(KeyEvent ev) {
    if (ev.getKeyCode() != 0) {
    keyTrigger = ev.getKeyCode();
    txtTrigger.setText(ev.getKeyText(keyTrigger));
}
}

@Override
public void keyTyped(KeyEvent ev) {
    txtTrigger.setText("");
}

However it looks horrible when you press special keys like F1--12 or Ctrl because it keeps the last typed non-special key (for example, if you press 'T' and then 'Ctrl', the text in the field keeps being 't' until you release the 'Ctrl' key).

This is the code so far for the JTextField:

txtTrigger = new JTextField();
txtTrigger.setColumns(10);
txtTrigger.addKeyListener(this);
txtTrigger.setBounds(80, 5, 64, 20);
contentPane.add(txtTrigger);

What I want is the field to be empty until you release the key. How can I get the application working this way?

4

2 に答える 2

1

I don't think a editable text field is your best choice here. What I've done in the past is basically faked it.

I've generated a custom component that "looks" like a JTextField and, using my own KeyListener, I've added elements to the view (I did my own "key" renderer, but you could simply have a list of String elements that you can render).

Basically, when keyPressed is triggered, I would add the key code to a list (taking into consideration things like its modifier state). If another key event is triggered with the same key code, then you can ignore it.

When keyReleased is triggered, you can remove that keycode from the active list.

于 2013-03-24T23:53:44.273 に答える
0

You can add the keylistener to the jframe or many components... Just make sure that component has the focus.

于 2013-03-25T00:04:33.380 に答える