【发布时间】:2016-10-11 21:35:16
【问题描述】:
我的 ComboBox 有许多字符串对象,例如(“David”、“John”、“Mary”、“Gabriel”、“Anderson”、“Henry”、“Johnson”、“Halstead”、“Annie” ,“禧年”)。 组合框是可编辑的。 所以,无论我在组合框中写什么,在下拉选项中,我都应该只获得与组合框中键入的字符串匹配的字符串对象。 假设,如果我在 Combobox 字段中输入了“An”,那么 ComboBox 列表中应该只有 Annie 和 Anderson。A
public void setEditor(ComboBoxEditor editor){
super.setEditor(editor);
setEditable(true);
if (editor.getEditorComponent() instanceof JTextField) {
inputField = (JTextField) editor.getEditorComponent();
inputField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e){
char key = e.getKeyChar();
String[] matchedString;
if(Character.isLetterOrDigit(key)||Character.isSpaceChar(key)||key=='\b'){
if(key=='\b'){
matchedString = getMatchedItems(inputField.getText());
removeAllItems();
for(int i=0; i<matchedString.length; i++){
addItem(matchedString[i]);
}
}
else{
matchedString = getMatchedItems(inputField.getText()+key);
removeAllItems();
for(int i=0; i<matchedString.length; i++){
addItem(matchedString[i]);
}
}
}
}
private int getMatchedCount(String currentWord) {
int n = getItemCount(),count=0;
for(int i=0; i<n; i++){
if(((String)getItemAt(i)).toLowerCase().startsWith(currentWord.toLowerCase())){
count++;
}
}
return count;
}
private String[] getMatchedItems(String currentWord){
int n = getItemCount(),k=0;
String[] matchedString = new String[getMatchedCount(currentWord)];
for(int i=0;i<n;i++){
if(((String)getItemAt(i)).toLowerCase().startsWith(currentWord.toLowerCase())){
matchedString[k++] = (String)getItemAt(i);
}
}
return matchedString;
}
});
}
}
public static void main(String[] args) {
JFrame fr=new JFrame();
fr.setLayout(null);
/*List <String> list = new ArrayList<String>();
list.add("Shahroz");
list.add("Wasif");
list.add("Akram");
*/
String str[] = {"Shahroz","saleem","Khan","Wasif","Dutta","Piyush","Rajat","Rehan","Rajesh"};
fr.add(new AutoCombo(str));
fr.setSize(400, 800);
fr.setVisible(true);
}
}
【问题讨论】:
-
但问题是什么?
-
我投票结束这个问题作为离题,因为它是代码编写请求,没有任何问题描述阻止 OP 自己编写它。