DjayPediA
DjayPediA

Reputation: 17

JAVA: conditioning String to comboBox items, it is possible?

I am trying to make an if conditional statement that will compare my textfield FillUnitTextTag to jcombobox cmbBox_PurchsUnit's items so that, no redundant items will be added to the combobox.

my FillUnitTextTag textfield is the field were I can add item(s) to the comboBox cmbBox_PurchsUnit but it also keeps the existing one(intentional).

How may I get rid of it?

here's my actual code:

 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();
        }
    }
}

Thanks in advance!

Upvotes: 1

Views: 254

Answers (2)

DjayPediA
DjayPediA

Reputation: 17

How about:

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

        cmbBoxmodel.getElementAt(dis);
        }

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  • Get the JComboBox's model via its getModel() method,
  • then loop through the model using a for loop comparing Strings in the model vs the String to add.
  • The model has a getSize() method that tells you how many times to loop
  • And it has a getElementAt(int index) method that allows you to get each item in the model for comparison.

In pseudocode (since again, you're better off writing your own code):

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

Upvotes: 2

Related Questions