Java 更改 JComboBox 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/396896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing the Contents of the JComboBox
提问by acostache
I would like to change the contents of the list of a JComboBox
(like adding another list in place of and older one). Is there any way I might be able to do that?
Thanks in advance!
我想更改 a 列表的内容JComboBox
(例如添加另一个列表代替旧列表)。有什么办法可以做到吗?提前致谢!
采纳答案by Uri
If you want to be able to add and remove items from an existing combo box at runtime, the underlying data model for the combo box needs to be a MutableComboBoxModel
如果您希望能够在运行时从现有组合框中添加和删除项目,组合框的底层数据模型需要是 MutableComboBoxModel
Google for that class for interface information and for examples of how to use it.
谷歌为该类的接口信息和如何使用它的例子。
Note that if you want the user to type in new values, you also need to make the box editable.
请注意,如果您希望用户输入新值,您还需要使该框可编辑。
You can find some links to examples here.
您可以在此处找到一些示例链接。
回答by Uri
Of course you can. There are several methods for manipulating JComboBoxes using the default list model. Have a look at the remove* methods and add* methods:
当然可以。有多种使用默认列表模型操作 JComboBox 的方法。看看 remove* 方法和 add* 方法:
http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.html
http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.html
回答by Phil
You can also replace the model in its entirety with setModel().
您还可以使用 setModel() 完全替换模型。
But after writing more and more user interfaces, I find it more useful to write a custom ComboBoxModel to wrap the data structure the ComboBox is presenting. This is more unit testable and cleaner, IMHO.
但是在编写了越来越多的用户界面之后,我发现编写自定义 ComboBoxModel 来包装 ComboBox 呈现的数据结构更有用。恕我直言,这更易于单元测试和清洁。
回答by Barend
The Glazed Listslibrary is mighty helpful when you want to wire any sort of mutable list to a GUI control. It's a large-ish library which may not be appropriate for your project, but take a look at their screencasts and judge for yourself. It supports a lot of related stuff like filtering and auto-completion and can save you a lot of manual work.
当您想将任何类型的可变列表连接到 GUI 控件时,Glazed Lists库非常有用。这是一个大型图书馆,可能不适合您的项目,但请查看他们的截屏视频并自行判断。它支持很多相关的东西,比如过滤和自动完成,可以为你节省大量的手动工作。
回答by pal
I found this thread and came up with a quick (and probably dirty) solution:
我找到了这个线程并提出了一个快速(可能很脏)的解决方案:
oldComboBox.setModel(new JComboBox<>(new_items).getModel());