Karl Giesing
Karl Giesing

Reputation: 1654

Checking whether a JComboBox has the default value or not

EDIT: Since the term "default value" is confusing, I changed it to "initial value."

This is sort of an interesting question. I searched on the site for an answer, but didn't find one.

I'm writing a validator class in Java, and one of the things I'd like to validate is whether or not a JComboBox has its initial value.

Note, that I am not checking to see whether the user has selected a value; merely if the value that the user selected, is the same as the initial value.

For example, let's say the options are:

Some Message Here
Item 1
Item 2
Item 3

...etc. The "Some Message Here" text would be the initial value, and I would make it so using the setSelectedIndex or setSelectedItem methods.

The problem is, once the user selects another item (say, Item 1), then there is no longer any way to tell what the initial value was supposed to be.

I can't just check for a "magic number" (like, say, if (cb.getSelectedIndex() == 0) ) because the validator class has no way of knowing if the value at index 0 is, in fact, what the initial value is supposed to be. (And it may not be, for example in a list of U.S. states.)

Nor can I use any of the event listeners. Think of a situation where the user selects "Item 1", then re-selects "Some Message Here". I would want this to fail validation.

Any ideas?

Upvotes: 2

Views: 1191

Answers (1)

Karl Giesing
Karl Giesing

Reputation: 1654

For the record, here's what I ended up doing:

I took JB Nizet's advice, and had the coder pass the initial value to the static validator class, e.g.:

Validator.isDefault(myComboBox, myInitialIndex);

However, I also overloaded it such that you can simply call it with the JComboBox, and the index will default to 0:

Validator.isDefault(myComboBox); // same as Validator.isDefault(myComboBox, 0);

I'll probably also overload it so that it takes a String as a second argument (and checks it using getSelectedItem()).

If there's a better way to do it, I don't know what it would be.

Upvotes: 1

Related Questions