呵呵,我也写了个,还在调试着,对于出错目前还没有找到解决方法。
大家帮我看看,谢谢。
/** An auto-complete JComboBox */
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
class BasicAutoCombo extends JComboBox implementsdo
cumentListener{
public BasicAutoCombo(){
super();
init();
}
public BasicAutoCombo(Object[] items){
super(items);
init();
}
void init(){
this.setEditable(true);
((JTextField)this.getEditor().getEditorComponent()).getDocument().addDocumentListener(this);
}
public void changedUpdate(DocumentEvent e){System.out.println("Chan1ged");}
public void insertUpdate(DocumentEvent e){System.out.println("Chan2ged");}
public void removeUpdate(DocumentEvent e){System.out.println("Chan3ged");}
}
public class AutoCombo extends BasicAutoCombo{
public AutoCombo(){
super();
}
public AutoCombo(Object[] items){
super(items);
}
public void insertUpdate(DocumentEvent e){
doLookup();
}
public void removeUpdate(DocumentEvent e){
doLookup();
}
voiddo
Lookup(){
this.showPopup();
String curItem = (String)this.getEditor().getItem();
int itemCount = this.getItemCount();
for (int i = 0;
i < itemCount;
i++){
String tmpItem = (String)this.getItemAt(i);
if (tmpItem.startsWith(curItem)){
try {
/** setSelectedItem() 总出错,怎么办?*/
this.setSelectedItem(tmpItem);
this.getEditor().setItem(tmpItem);
((JTextField)this.getEditor()).setCaretPosition(curItem.length());
((JTextField)this.getEditor()).moveCaretPosition(tmpItem.length());
} catch (Exception ex){ System.out.println("Error setting index");
}
break;
}
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Test");
String[] items = {"Abstract", "Abound", "About", "Account", "Accuse"};
AutoCombo ac = new AutoCombo(items);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(ac);
frame.pack();
frame.setVisible(true);
}
}