• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 263
  • Last Modified:

Is there a way to add entries into a combobox and check they are not repeated?

That's actually my question. I'm using Netbeans 3.6, thanks
0
hacktek
Asked:
hacktek
  • 2
1 Solution
 
mmuruganandamCommented:
You have to extend the "javax.swing.DefaultComboBoxModel" and have to write your custom model.

in the addElement method, you have to check for the element's existence, if it is not present,
then you can add the element.


Otherwise, you can ignore the element.


Regards,
Muruga
0
 
mmuruganandamCommented:
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;

public class UniqueElementComboBoxModel extends DefaultComboBoxModel
{
      public UniqueElementComboBoxModel()
      {
            super();
      }

      public UniqueElementComboBoxModel(Object items[])
      {
            this();

            int i, c;
            for (i = 0, c = items.length; i < c; i++)
                  addElement(items[i]);

            if (getSize() > 0)
            {
                  setSelectedItem(getElementAt(0));
            }
      }

      public UniqueElementComboBoxModel(Vector v)
      {
            this();

            int size = v.size();

            for (int i = 0; i < size; i++)
            {
                  addElement(v.get(i));
            }

            if (getSize() > 0)
            {
                  setSelectedItem(getElementAt(0));
            }
      }

      public void addElement(Object anObject)
      {
            if (getIndexOf(anObject) < 0)
            {
                  super.addElement(anObject);
            }
      }

      public void insertElementAt(Object anObject, int index)
      {
            if (getIndexOf(anObject) < 0)
            {
                  super.insertElementAt(anObject, index);
            }
      }
}


Here is the model, that maintains the uniqueness of the data.


Regards,
Muruga
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now