Java SWT: Apply Key Events from List to Text field
I am making a component in SWT that contains a textbox and a list box. Whenever text is entered, it filters the list. Everything works fine so far and I'm just trying to add some nice usability features.
What I want to do is listen for any key events in the List box if it is pressing Enter. I am doing the action "ok" (already done) but otherwise I want the focus to change to the textbox and the key event raised there. Basically if the focus is on the List box and the user enters something I want it to be automatically entered into the text box.
Responding to a KeyPressed or keyReleased event is fine for setting focus to a textbox, but I need to then repeat the keyEvent so that in fact whatever was typed was typed. Any ideas?
source to share
So this is what I did:
itemList.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.keyCode == '\r' || e.keyCode == SWT.KEYPAD_CR) {
okButtonAction();
} else if (e.keyCode == SWT.ARROW_UP || e.keyCode == SWT.ARROW_DOWN || e.keyCode == SWT.ARROW_LEFT || e.keyCode == SWT.ARROW_RIGHT) {
super.keyReleased(e);
} else if (e.character > 0) {
filterInput.setFocus();
Event event = new Event();
event.type = SWT.KeyDown;
event.keyCode = e.keyCode;
event.character = e.character;
Display.getCurrent().post(event);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
event.type = SWT.KeyUp;
Display.getCurrent().post(event);
}
}
});
I read that the Display.post method was there to automatically test the GUI, but it works for me here, so I'll use it if anyone can't give me a good reason why not.
source to share
My first idea was that there might be a way to restart the key event (or fire a copy of it) in the textbox. But that may not give the desired result, because there are some key events that you probably don't want to pass from the list to text, for example. pressing the up and down arrow keys to navigate through the list.
So, you have to decide which key events trigger the focus transfer. From your question, I understand that you are implementing a text filter, so you should restrict the transmission of text characters. When you know the entered character, you can manually add it to the filter text (or insert it at the cursor position of the text box).
source to share