views:

37

answers:

2

Hi, what is the easiest way to listen for key presses from the user? Specifically I am writing an image viewer program that uses a JFileChooser to select images and on the left side, a JList that shows the contents of the director. I would like to make the arrow kets (left/right) move to the next/previous file.

Thank you in advance.

+2  A: 

It sounds like you need a KeyListener. The linked tutorial also talks about focus, which will be important to ensure your key events are trapped by the right handler.

Gian
okay, so I need to give my window focus or my imageIcon where I am displaying my image? Or should I switch it to a Graphic and give that focus? I am confused..
Cody
You need to give focus to whatever component has the action listener attached to it that you want to be invoked by a keypress. The key bindings approach suggested in another answer might be fruitful in this regard too if you can work what you what to do into that idiom.
Gian
+1  A: 

Swing was designed to use Key Bindings.

In fact a JList already supports the up/down keys to move to the next item in the list. You can easily map these Actions to the left/right keys.

camickr