Re: Possible to have JList navigation keystrokes while JTextField
has focus.
Daniel Pitts wrote:
I have a JTextField which the user can enter data, and this affects the
state of a JList.
I'd like the user to be able to type in the JTextField, but then press
the up-arrow or down-arrow to adjust the current selection.
What would be the best approach? I can listen for the up/down keystrokes
myself, and adjust the selection myself, but that seems to be a
short-cut hack that might lead to inconsistent behavior.
Is there another approach?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test {
private void createAndShowGUI() {
final JList list = new JList(new String[]{"A", "B", "C"});
InputMap im =
list.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0),
"selectNextRow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),
"selectPreviousRow");
list.setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, im);
JTextField textField = new JTextField(20);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new JScrollPane(list));
frame.add(textField, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static final void main(String args[]) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test().createAndShowGUI();
}
});
}
}
HTH
Michael