java 从 JList 取回数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15568646/
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
Getting back data from JList
提问by Andrew
I was googling for a solution to retrieve data back from a JList component, but didn't find any.So, is there a method of Jlist that return its items? I don't want just a selected one. I want the whole list.
我在谷歌上搜索从 JList 组件取回数据的解决方案,但没有找到。我不想要一个选定的。我想要整个列表。
The reason is I have this method that updates all the components of a dialogbox base on the selected value of a list box. I want to update that list box from the same method. So to do that, the method should not update the list box whenever it gets called. It should compare the values in the list box with the most recent data that I store in one class.(goes into infinite loop otherwise) Only when data in the list box doesn't match with the data in the class, it gets updated.
原因是我有这个方法可以根据列表框的选定值更新对话框的所有组件。我想用同样的方法更新那个列表框。因此,要做到这一点,该方法不应在被调用时更新列表框。它应该将列表框中的值与我存储在一个类中的最新数据进行比较。(否则进入无限循环)只有当列表框中的数据与类中的数据不匹配时,它才会更新。
Is there such method to retrieve all the data of list box?
有没有这样的方法来检索列表框的所有数据?
回答by Varun
You have to use the getModel() method to get the model data and then use the methods inside ListModel in order to get all the data elements.
您必须使用 getModel() 方法来获取模型数据,然后使用 ListModel 中的方法来获取所有数据元素。
ListModel model = list.getModel();
for(int i=0; i < model.getSize(); i++){
Object o = model.getElementAt(i);
}
http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html#getModel()
http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html#getModel()
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.html
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.html
回答by JustDanyul
To get the selections, you will need to use a combination of getModel
and getSelectedIndices
要获得选择,您需要使用getModel
和getSelectedIndices
ListModel model = jListInstance.getModel();
for(int index : jListInstance.getSelectedIndices()) {
System.out.println(model.getElementAt(index));
}
回答by user_CC
Use the getModel()method to retrieve the data model that is contained within the JList. The List model can be traversed in the following manner:
使用getModel()方法检索 JList 中包含的数据模型。List 模型可以通过以下方式遍历:
ListModel list = jListObj.getModel();
for(int i = 0; i < list.getSize(); i++){
Object obj = list.getElemenetAt(i);
}
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.htmlhttp://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html#getModel%28%29
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListModel.html http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html #getModel%28%29