可编辑的Jcombobox不填充数据库中的数据

时间:2013-03-25 05:31:01

标签: java swing jcombobox comboboxmodel

在我的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())
        );

1 个答案:

答案 0 :(得分:2)

您可以编写如下代码:

ArrayList<String> transList = PvtTransDriverController.getPvtTransporterNames();
ComboBoxModel comboBoxModel = new DefaultComboBoxModel(transList.toArray());
cmbPvtTrnsCompanySeacrh.setModel(comboBoxModel );