JComboBox search for match list
Hi, here again :)
I am trying to search equivalent list in JCombobox based on user input. JComboBox is set to editable. JComboBox' KeyListener does not work, ActionListener works on lost focus. I have no idea what to search in google. I am totally clueless now.
Here is what I try:
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JComboTrial extends JFrame implements ActionListener, KeyListener
{ JComboBox jc1 = null;
JButton b1 = new JButton("OK");
JPanel p = new JPanel();
public JComboTrial()
{ String[] strList = {"DE 0001", "DF 0504", "DF 0604", "FR 5971", "GE 0587", "GKL 684"};
jc1 = new JComboBox(strList);
jc1.addActionListener(this);
jc1.addKeyListener(this);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.add(p, BorderLayout.CENTER);
p.setLayout(new BorderLayout());
p.add(jc1, BorderLayout.CENTER);
p.add(b1, BorderLayout.LINE_END);
pack();
jc1.setEditable(true);
}
public void actionPerformed(ActionEvent ae)
{ System.out.println("From Action event");
cmbSelectInput(jc1, jc1.getSelectedItem().toString());
}
public void keyTyped(KeyEvent ae)
{ System.out.println("FROM Typed");
cmbSelectInput(jc1, jc1.getSelectedItem().toString());
}
public void keyPressed(KeyEvent ae)
{ System.out.println("FROM Pressed");
cmbSelectInput(jc1, jc1.getSelectedItem().toString());
}
public void keyReleased(KeyEvent ae)
{ System.out.println("FROM Released");
cmbSelectInput(jc1, jc1.getSelectedItem().toString());
}
void cmbSelectInput(JComboBox combo, String input)
{ int cmb_count = combo.getItemCount() - 1;
int inputlen = combo.getSelectedItem().toString().length()-1;
String combo_item = null;
for(int i=0; i < cmb_count; i++)
{ combo_item = combo.getItemAt(i).toString().substring(0, inputlen);
if(input.equals(combo_item))
{ combo.setSelectedIndex(i);
break;
}
}
}//end of cmbSelectInput
public static void main(String[] args)
{ new JComboTrial().setVisible(true);
}
}
Thanks in advance,
geje