I am making a component in SWT that contains a text field and a list. Whenever text is entered it filters the list. So far everything is working great and I am just trying to add some nice usability features.
What I want to do is listen for any key events in the List field, if it is Enter that is pressed I perform the 'ok' action (already done) but otherwise I want focus to change to the text field and have the key event triggered there. Basically, if the focus 开发者_JAVA百科is on the List field and the user types something I want it to be automatically typed into the text field.
Responding to the keyPressed or keyReleased event is fine for setting the focus to the text field, but I need to then repeat the keyEvent somehow so that whatever was typed is actually entered. Any ideas?
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 for doing automatic GUI testing, but it works for my purpose here, so I will use it unless anyone can give me a good reason why not??
My first idea was that there may be a way to re-fire the key event (or fire a copy of it) to the text field. But that may not yield the desired result, because there are some key events you probably don't want transferred from the list to the text, e.g. pressing the Up and Down arrow keys for navigation within the list.
So you should 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 transfer to text characters. Once you know the character that was entered, you may append it to the filter text manually (or insert at the cursor position of the text field).
精彩评论