JAVA:调整String到comboBox项目,有可能吗?

时间:2015-08-12 15:51:13

标签: java swing combobox

我正在尝试制作一个if条件语句,将我的文本字段FillUnitTextTag与jcombobox cmbBox_PurchsUnit的项目进行比较,以便不会将多余的项目添加到组合框中。< / p>

my FillUnitTextTag textfield是我可以将项目添加到comboBox cmbBox_PurchsUnit的字段,但它也保留现有的(有意)。

我怎么能摆脱它?

这是我的实际代码:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if(FillUnitTextTag.getText().equals(cmbBox_PurchsUnit.getSelectedIndex())){
        JOptionPane.showMessageDialog(null, "Item is already in the combobox");
    } else {
        int p = JOptionPane.showConfirmDialog(null, FillUnitTextTag.getText()+" will be added to units.\n"
            + "Do want to continue?","", JOptionPane.YES_NO_OPTION);
        if(p==0){
            cmbBox_PurchsUnit.addItem(FillUnitTextTag.getText());
            cmbBox_PurchsUnit.setSelectedItem(FillUnitTextTag.getText());
            UnitPopUp.dispose();
        }
    }
}

提前致谢!

2 个答案:

答案 0 :(得分:2)

  • 通过getModel()方法
  • 获取JComboBox的模型
  • 然后使用for循环遍历模型,比较模型中的字符串与要添加的字符串。
  • 模型有getSize()方法,可以告诉您循环次数
  • 它有一个getElementAt(int index)方法,可让您获取模型中的每个项目以进行比较。

在伪代码中(再次,你最好编写自己的代码):

set a boolean variable, okToAdd to true
Get your combo box's model by calling getModel() on it.  
create a for loop that loops from 0 to the size of the model, which you get by calling getSize()  
    in the loop get each item from the model via getElementAt(int index)
    compare the item to the String of interest via the equals(...) method
    If they match then change okToAdd to false  
end of for loop.
If okToAdd is true, add String to the combo box's model

答案 1 :(得分:0)

怎么样:

ComboBoxModel cmbBoxmodel = cmbBox_PurchsUnit.getModel();
        cmbBoxmodel.getSize();
        for(int dis=0;dis<=cmbBoxmodel.getSize();dis++){

        cmbBoxmodel.getElementAt(dis);
        }