我的组合框有很多字符串对象让我们说一个实例(“David”,“John”,“Mary”,“Gabriel”,“Anderson”,“Henry”,“Johnson”,“Halstead” “安妮”,“银禧”)。 组合框是可编辑的。 所以,无论我在comboBox中写入,在下拉选项中,我应该只获取与在comboBox中键入的字符串匹配的字符串对象。 比方说,如果我在Combobox字段中输入了“An”,那么ComboBox列表中应该只有Annie和Anderson。下拉组合框
这与AutoCompleteComboBox不同。所以,请不要欢迎这样的答案。
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);
}
}
但问题是什么? – Pshemo
我正在投票结束这个问题作为题外话题,因为它是代码写入请求,没有任何描述停止OP写它自己的问题的描述。 – Pshemo