是Jlist自动覆盖列表? (错误)?
我希望我会得到帮助,我会问一般问题:
我正在使用JList
,并且由于JList
没有(值,文本)(所以我可以显示文本并使用我的代码中的值)。 由于这个泄漏,我创建了对象(myList) List
,它与JList
并行工作。 我添加到JList
每个项目都添加到myList
,因此相同的索引将在两个对象(JList和mylist)中包含相同的信息我使用JList.getselectedindex()
方法获取索引并在myList
用于pup信息…
问题是:当我选择值时, myList
的下一个值被第一个值覆盖!!! 这个问题已知吗?
mod_mp = new ModelMAPPING(); objects cotain values that ot exist in jList msgF.setTo(incom.userID);/////// set parter! if(isExCon==-1) { // not exist mod_mp.to = incom.userID; // incom is object that incom from another program mod_mp.SetCovFile(incom.userID+".html"); mod_mp.ConvName = incom.getBody(); boolean added= model_list.add(mod_mp); // add to mylist if(added) System.out.println(mod_mp._Hfile + " added"); model.addElement(mod_mp.ConvName);// add to Jlist by model HestoryFile(Htmlhead+tohis,mod_mp._Hfile);//create _Hfile and write to it:"tohis" string. } else { //exist@ // note isExcon return the index if exist else -1 model_list.get(isExCon).ConvName=incom.getBody(); mod_mp.SetCovFile(model_list.get(isExCon)._Hfile); HestoryFile(tohis, model_list.get(isExCon)._Hfile); }//end else
如果文件存在,我只需更新JList
的新文本并设置当前文件
JList
的选择是:
msgF.setTo (model_list.get(jList2.getSelectedIndex()).to); // set that we will send To... mod_mp.SetCovFile(model_list.get(jList2.getSelectedIndex())._Hfile);//set the file jLabel5.setText( bringFromFile(mod_mp._Hfile));//tell the label to read that file
它工作正常,但当我在JList
有两个项目,如果我选择任何一个,另一个被覆盖!
我正在使用
JList
,并且由于JList
没有(值,文本)(所以我可以显示文本并使用我的代码中的值)
很难理解你的问题,但我“怀疑”引用的行,你在JList
模型和JList
本身显示的文本之间有一个误解。 我想这就是为什么你有一个单独的List
。
模型可以包含您想要的任何对象,无论对象本身如何, JList
也可以根据需要显示文本。 最后一项任务由ListCellRenderer完成。 看一看编写自定义单元格渲染器
例如,你可以拥有这个类:
class Person { String lastName; String name; public Person(String lastName, String name){ this.lastName = lastName; this.name = name; } public String getLastName(){ return this.lastName; } public String getName(){ return this.name; } }
现在,您希望JList
使Person
对象稍后与它们一起使用。 这部分很简单,只需创建一个ListModel
并在其中添加元素:
DefaultListModel model = new DefaultListModel(); model.addElement(new Person("Lennon","John")); model.addElement(new Person("Harrison","George")); model.addElement(new Person("McCartney","Paul")); model.addElement(new Person("Starr","Ringo"));
但是您想显示每个Person
的名称和姓氏。 那么你可以实现自己的ListCellRenderer
来做到这一点:
JList list = new JList(model); list.setCellRenderer(new DefaultListCellRenderer(){ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if(value instanceof Person){ Person person = (Person)value; setText(person.getName() + " " + person.getLastName()); } return this; } });
您的JList
将根据需要显示项目: