在我的Java swing应用程序中,我希望Jcombobox填充来自数据库的一些数据,并允许用户输入他们希望的关键字以便使用组合框值进行搜索。所以我将可编辑模式设置为true.But然后我丢失了来自数据库的数据。是否可以启用可编辑模式为true并同时使用数据库中的数据填充Jcomobobox?
private void cmbPvtTrnsCompanySeacrhFocusGained(java.awt.event.FocusEvent evt) {
try {
ArrayList<String> transList = PvtTransDriverController.getPvtTransporterNames();
ComboBoxModel comboBoxModel = new DefaultComboBoxModel(transList.toArray());
cmbPvtTrnsCompanySeacrh.setModel(comboBoxModel);
} catch (ClassNotFoundException ex) {
Logger.getLogger(PvtTransDriver.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(PvtTransDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
cmbPvtTrnsCompanySeacrh
cmbPvtTrnsCompanySeacrh.setEditable(true);
cmbPvtTrnsCompanySeacrh.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
cmbPvtTrnsCompanySeacrhFocusGained(evt);
}
});
javax.swing.GroupLayout jPanel23Layout = new javax.swing.GroupLayout(jPanel23);
jPanel23.setLayout(jPanel23Layout);
jPanel23Layout.setHorizontalGroup(
jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel23Layout.createSequentialGroup()
.addContainerGap()
.addComponent(cmbPvtTrnsCompanySeacrh, 0, 266, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
答案 0 :(得分:2)
您可以编写如下代码:
ArrayList<String> transList = PvtTransDriverController.getPvtTransporterNames();
ComboBoxModel comboBoxModel = new DefaultComboBoxModel(transList.toArray());
cmbPvtTrnsCompanySeacrh.setModel(comboBoxModel );