我有一个启用的Combobox,因此用户可以输入文字。当他们输入一封信时,应该会出现自动提示/自动填充。我有以下代码,但由于某种原因,它不起作用。我认为问题是addKeyListener
因为它会显示弹出窗口。
public class NewJFrame1 extends javax.swing.JFrame {
String Pesawat [] = {"Epping","Lion Air","Lufthansa Air","Batavia Air","Bali Air"};
Vector vectorPesawat = new Vector();
/**
* Creates new form NewJFrame1
*/
public NewJFrame1() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setEditable(true);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(Pesawat) );
jComboBox1.setSelectedIndex(-1);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(111, 111, 111)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(166, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(222, Short.MAX_VALUE))
);
jComboBox1.addKeyListener(new ComboListener(jComboBox1,vectorPesawat));
pack();
ComboListener
的文件是:
public class ComboListener extends KeyAdapter {
@SuppressWarnings("rawtypes")
JComboBox cbListener;
@SuppressWarnings("rawtypes")
Vector vector;
@SuppressWarnings("rawtypes")
public ComboListener(JComboBox cbListenerParam, Vector vectorParam) {
cbListener = cbListenerParam;
vector = vectorParam;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void keyTyped(KeyEvent key) {
// TODO Auto-generated method stub
String text = ((JTextField)key.getSource()).getText();
cbListener.setModel(new DefaultComboBoxModel(getFilteredList(text)));
cbListener.setSelectedIndex(-1);
((JTextField)cbListener.getEditor().getEditorComponent()).setText(text);
cbListener.showPopup();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Vector getFilteredList(String text) {
Vector v = new Vector();
for (int a = 0; a<vector.size(); a++) {
if (vector.get(a).toString().startsWith(text)) {
v.add(vector.get(a).toString());
}
}
return v;
}
}