I wnt that when i enter some letter in the textfield then the related items should be picked up from my database and should appear as a drop down list. For Example: I typed 'J' in text Field, in my database is having names such as {"Juby','Jaz','Jasmine','Joggy'....} Theses names should appear as a list. So that i could select one from them.and so on for other leters as well. Is there any predefined control in awt?? Thnx
+1
A:
This is a small example implementing what ( i think) you asked for.. the database in this example is a vector of strings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Answer extends JFrame {
public static final int MAXITEMS =100;
JPanel panel = new JPanel();
JTextField textField = new JTextField(10);
String[] myDataBase = {"Juby","Jaz","Jasmine","Joggy","one","dog", "cat" ,"parot"};
String[] listItems;
JList theList = new JList() ;
public Answer() {
this.add(panel);
panel.setPreferredSize(new Dimension(500,300));
panel.add(textField);
panel.add(theList);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
String compareString = textField.getText()+ke.getKeyChar();
listItems = new String[MAXITEMS];
int counter = 0;
for (int i = 0 ; i <myDataBase.length ; i++){
if (counter < MAXITEMS){
if (myDataBase[i].substring(0, compareString.length()).equals(compareString)){
listItems[counter] = myDataBase[i];
counter++;
}
}
}
theList.setListData(listItems);
}
});
}
public static void main(String[] args) {
final Answer answer = new Answer();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
answer.pack();
answer.setVisible(true);
}
});
}
}
Pitelk
2009-08-01 14:11:36
I tried the code but its not working
2009-08-01 14:29:47
Mind that a lower case letter is different from an upper one, meaning that in order to see the words "Juby","Jaz","Jasmine" you should use "J" and not j.I copy pasted the code and it works allright. Do you have an error message.. and if you do what exactly does it say?
Pitelk
2009-08-01 15:37:37
+1
A:
One option is to use GlazedLists, as it has some support for auto-completion.
kd304
2009-08-01 15:20:20
+1
A:
Why not just use a JComboBox? By default, when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item.
Or you could set the JComboBox to be editable using setEditable(true)
, and use a KeySelectionManager. The link explains selecting an item in a JComboBox component with multiple keystrokes.
OMG Ponies
2009-08-02 04:33:56