JComboBox JComponent의 하위 클래스입니다. 클래스이며 텍스트 필드 의 조합입니다. 및 드롭다운 목록 사용자가 값을 선택할 수 있는 항목 . JComboBox는 ActionListener, ChangeListener,를 생성할 수 있습니다. 및 ItemListener 사용자가 콤보 상자에서 작업할 때 인터페이스입니다.
자동 완성 JComboBox를 구현할 수 있습니다. 사용자가 콤보 상자의 사용자 지정(AutoCompleteComboBox)을 사용하여 키보드에서 입력 값을 입력할 때 ) JComboBox 확장 수업.
예시
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class AutoCompleteComboBoxTest extends JFrame {
private JComboBox comboBox;
public AutoCompleteComboBoxTest() {
setTitle("AutoCompleteComboBox");
String[] countries = new String[] {"india", "australia", "newzealand", "england", "germany",
"france", "ireland", "southafrica", "bangladesh", "holland", "america"};
comboBox = new AutoCompleteComboBox(countries);
add(comboBox, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String []args) {
new AutoCompleteComboBoxTest();
}
}
// Implementtion of AutoCompleteComboBox
class AutoCompleteComboBox extends JComboBox {
public int caretPos = 0;
public JTextField tfield = null;
public AutoCompleteComboBox(final Object countries[]) {
super(countries);
setEditor(new BasicComboBoxEditor());
setEditable(true);
}
public void setSelectedIndex(int index) {
super.setSelectedIndex(index);
tfield.setText(getItemAt(index).toString());
tfield.setSelectionEnd(caretPos + tfield.getText().length());
tfield.moveCaretPosition(caretPos);
}
public void setEditor(ComboBoxEditor editor) {
super.setEditor(editor);
if(editor.getEditorComponent() instanceof JTextField) {
tfield = (JTextField) editor.getEditorComponent();
tfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
char key = ke.getKeyChar();
if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
caretPos = tfield.getCaretPosition();
String text="";
try {
text = tfield.getText(0, caretPos);
} catch (javax.swing.text.BadLocationException e) {
e.printStackTrace();
}
for (int i=0; i < getItemCount(); i++) {
String element = (String) getItemAt(i);
if (element.startsWith(text)) {
setSelectedIndex(i);
return;
}
}
}
});
}
}
} 출력
