检查 JComboBox 是否具有默认值
编辑:由于术语“默认值”令人困惑,我将其更改为“初始值”。
这是一个有趣的问题。我在网站上搜索了答案,但没有找到。
我正在用 Java 编写一个验证器类,我想要验证的事情之一是 JComboBox 是否具有其初始值。
请注意,我不检查用户是否选择了一个值;仅当用户选择的值与初始值相同时。
例如,假设选项是:
Some Message Here
Item 1
Item 2
Item 3
...等。 “Some Message Here”文本将是初始值,我将使用 setSelectedIndex 或 setSelectedItem 方法将其设置为初始值。
问题是,一旦用户选择了另一个项目(例如,项目 1),就不再有任何方法可以告诉初始值应该是什么。
我不能只检查“幻数”(例如 if (cb.getSelectedIndex() == 0)
),因为验证器类无法知道索引处的值是否事实上,0 就是初始值。 (它可能不是,例如在美国各州的列表中。)
我也不能使用任何事件侦听器。考虑这样一种情况:用户选择“Item 1”,然后重新选择“Some Message Here”。我希望这个验证失败。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为记录,这就是我最终所做的:
我采纳了 JB Nizet 的建议,并让编码器将初始值传递给静态验证器类,例如:
但是,我还重载了它,以便您可以简单地使用 JComboBox 调用它,并且索引将默认为 0:
我可能还会重载它,以便它采用 String 作为第二个参数(并使用
getSelectedItem()
检查它)。如果有更好的方法,我不知道会是什么。
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.:
However, I also overloaded it such that you can simply call it with the JComboBox, and the index will default to 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.