hello everybody! it is intresting! comboBox.addActionListener dont work! look at this, run this program, and type letters in comboBox. no "hello" is showing, and type letters in textField. "hello" is showing; thanks from befor
import java.awt.*; import java.awt.event.*; import javax.swing.*; cl*** Test extends JFrame { public Test() { super( "Customer" ); String s[] = {"five","six","seven"}; JComboBox co = new JComboBox(s); JTextField t = new JTextField(); Container c = getContentPane(); c.add( co, BorderLayout.NORTH ); c.add(t,BorderLayout.SOUTH); setSize(300,300);setVisible( true ); co.setEditable(true); t.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent k) { System.out.println("hello");} }); co.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent k) { System.out.println("hello");} }); } public static void main( String args[] ){ new Test(); } }
Hi JComboBox uses an editor to let you edit the content. So, when you are typing in JComboBox then it is firing key pressed events on the underlying editor and not the JComboBox. You need to add key listener to the underlying editor. To get the reference of that editor you can use getEditor().getEditorComponent() on you JComboBox. The following code works and it prints "hi" when you type in your combo box. Thanks Kishori
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ComboB extends JFrame {
public ComboB() {
super( "Customer" );
String s[] = {"five","six","seven"};
JComboBox co = new JComboBox(s);
JTextField t = new JTextField();
Container c = getContentPane();
c.add( co, BorderLayout.NORTH );
c.add(t,BorderLayout.SOUTH);
setSize(300,300);
setVisible( true );
co.setEditable(true);
t.addKeyListener(new KeyAdapter() {
publicvoid keyPressed(KeyEvent k){
System.out.println("hello");}
});
/* Don't use it
co.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k){
System.out.println("hello");
}
});
*/
/* Use the following */
co.getEditor().getEditorComponent().addKeyListener ( new KeyAdapter() {
publicvoid keyPressed(KeyEvent k){
System.out.println("hi");
}
} );
}
publicstaticvoid main( String args[] ){
new ComboB();
}
}