I need to have a comboBox that each time that letter, number or space written (release key), a string is returned with the text write inside the comboBox and without the need of press the Enter key.
Example: I press de “a” key and I release the key “a”, my String need to return “a” Next, I press the “b” key and I realise, my string return “ab” etc.
I use the code from: http://www.java2s.com/Tutorials/Java/Swing_How_to/JComboBox/Add_key_listener_to_Editable_JcomboBox_TextField.htm
And I added in the Key Released event:
Object value = combobox.getSelectedItem();
System.out.println("String: " + value);
In this case that work only if I press the Enter key but I don’t want that
Amy suggestions?
Thanks
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
//w ww.j a v a2 s . c om
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class SwingListenerDemo extends JFrame implements KeyListener {
JComboBox<String> combobox;
JComboBox<String> combobox1 = new JComboBox(new String[]{"b","b","c"});
public static void main(String[] args) {
new SwingListenerDemo();
}
private SwingListenerDemo() {
String[] options = {"Red", "Green", "Blue"};
combobox = new JComboBox<String>(options);
combobox.setEditable(true);
combobox.setSelectedIndex(-1);
combobox1.setEditable(true);
JTextField editor = (JTextField) combobox.getEditor().getEditorComponent();
System.out.println("editor" + editor);
editor.addKeyListener(this);
setLayout(new FlowLayout());
add(combobox);
add(combobox1);
pack();
setVisible(true);
}
public void keyTyped(KeyEvent arg0) {
System.out.println("Key Typed " + arg0.getKeyCode());
}
public void keyPressed(KeyEvent arg0) {
System.out.println("Key Pressed " + arg0.getKeyCode());
}
public void keyReleased(KeyEvent arg0) {
System.out.println("Key Released " + arg0.getKeyCode());
Object value = combobox.getSelectedItem();
System.out.println("String: " + value);
}
}