JComboBox:希望第一个条目为空白条目
我有一个 jcombobox,其值来自列表。我想将下拉列表中的第一个值设为空白。我处理它的方法是首先将列表类型的新对象放入其中,如示例所示:
final List<Object> list = getObjectsList();
list.add(new Object());
但这会导致空指针,如果
list.add(null);
这样做可以解决问题,但会在其他地方使用 Comparator 方法给我带来另一个问题。所以任何一轮的工作都会非常感谢。
I have a jcombobox which values come from a list. I want to first value to be blank from dropdown list. The way I approached it was by putting new object of the list type in first as example shows :
final List<Object> list = getObjectsList();
list.add(new Object());
But this results in null pointer and if do
list.add(null);
this solves the issue but then gives me another prob elsewhere with a Comparator method. So any work a rounds would be great thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以在添加项目之后、事件侦听器之前将所选索引设置为 -1。
如果您的 JcomboBox 使用泛型,此解决方案会更好。
You can also set the selected index to -1 after the items have been added, but before the event listener.
This solution will work better if your JcomboBox uses generics.
JComboBox.insertItemAt("", 0);
不适合您吗?您还需要为空白条目添加验证Doesn't
JComboBox.insertItemAt("", 0);
work for you? You need to add validation for the blank entry too恕我直言,这取决于您将如何处理这个“空条目”。几个想法:
尝试添加空字符串。
添加 object/null 并覆盖 getSelectedIndex() 方法。
IMHO it depends from what will you do with this "empty entry". Few ideas:
Try add empty string.
Add object/null AND override getSelectedIndex() method.