简体   繁体   English

从JList获取数据

[英]Getting back data from JList

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? 我正在谷歌搜索从JList组件检索数据的解决方案,但没有找到任何。所以,是否有一个Jlist的方法返回其项目? I don't want just a selected one. 我不想只选一个。 I want the whole list. 我想要整个清单。

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? 是否有这样的方法来检索列表框的所有数据?

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

To get the selections, you will need to use a combination of getModel and getSelectedIndices 要获得选择,您需要使用getModelgetSelectedIndices的组合

ListModel model = jListInstance.getModel();

for(int index : jListInstance.getSelectedIndices()) {
    System.out.println(model.getElementAt(index));
}

Use the getModel() method to retrieve the data model that is contained within the JList. 使用getModel()方法检索JList中包含的数据模型。 The List model can be traversed in the following manner: 可以通过以下方式遍历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.html http://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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM