1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
package referencehelptool;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
public class AutoComplete extends JComboBox implements JComboBox.KeySelectionManager{
private String searchFor;
private long lap;
public class CBDocument extends PlainDocument{
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException{
if (str==null) return;
super.insertString(offset, str, a);
if(!isPopupVisible() && str.length() != 0) fireActionEvent();
}
}
public AutoComplete(Object[] items){
super(items);
lap = new java.util.Date().getTime();
setKeySelectionManager(this);
JTextField tf;
if(getEditor() != null){
tf = (JTextField)getEditor().getEditorComponent();
if(tf != null){
tf.setDocument(new CBDocument());
addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
JTextField tf = (JTextField)getEditor().getEditorComponent();
String text = tf.getText();
ComboBoxModel aModel = getModel();
String current;
for(int i = 0; i < aModel.getSize(); i++){
current = aModel.getElementAt(i).toString();
if(current.toLowerCase().startsWith(text.toLowerCase())){
tf.setText(current);
tf.setSelectionStart(text.length());
tf.setSelectionEnd(current.length());
break;
}
}
}
});
}
}
}
public int selectionForKey(char aKey, ComboBoxModel aModel){
long now = new java.util.Date().getTime();
if (searchFor != null && aKey==KeyEvent.VK_BACK_SPACE && searchFor.length()>0){
searchFor = searchFor.substring(0, searchFor.length() -1);
}
else{
if(lap + 1000 < now)
searchFor = "" + aKey;
else
searchFor = searchFor + aKey;
}
lap = now;
String current;
for(int i = 0; i < aModel.getSize(); i++){
current = aModel.getElementAt(i).toString().toLowerCase();
if (current.toLowerCase().startsWith(searchFor.toLowerCase()))
return i;
}
return -1;
}
public void fireActionEvent(){
super.fireActionEvent();
}
public static void main(String arg[]){
JFrame f = new JFrame("AutoCompleteComboBox");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200,300);
Container cp= f.getContentPane();
cp.setLayout(null);
Locale[] locales = Locale.getAvailableLocales();
JComboBox cBox= new AutoComplete(locales);
cBox.setBounds(50,50,100,21);
cBox.setEditable(true);
cp.add(cBox);
f.setVisible(true);
}
public AutoComplete() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setFont(new java.awt.Font("Dialog", 1, 16));
this.setEditable(true);
this.setPopupVisible(true);
}
} |
Partager