我正在尝试制作一个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();
}
}
}
提前致谢!
答案 0 :(得分:2)
getModel()
方法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);
}