我想将List [i]的每个项目添加到不同的Jlist中,例如第一个jList会有Hello,bye,good,bad,nice,Ses,Iteme
我想制作4个不同的JList,
class List
{
Info[] List;
public void createList()
{
List = new Info[7];
List[0] = new Info("Hello",569.99,55,"jlas");
List[1] = new Info("bye",551.59,52,"byew");
List[2] = new Info("good",678.99,72,"good2");
List[3] = new Info("bad",4547.959,151,"bad2");
List[4] = new Info("nice",3554.99,235,"wii-U.jpg");
List[5] = new CInfo("Ses",1140.99,4,"das");
List[6] = new Info("Iteme",584.95,5,"sade");
}
}
答案 0 :(得分:2)
将所有值添加到ListModel
DefaultListModel model = new DefaultListModel();
for (Info info : List) {
model.addElement(model);
}
然后将此模型添加到每个JList
s ...
JList list1 = new JList(model);
JList list2 = new JList(model);
JList list3 = new JList(model);
JList list4 = new JList(model);
现在,这里有一个时髦的部分,为你想要显示数据的每种不同方式创建一个ListCellRenderer
......
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
public class ListTest {
public static void main(String[] args) {
}
public class InfoNameListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof Info) {
Info info = (Info)value;
value = info.getName(); // Or what ever getter you have available for such things
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
}
}
并将其应用于相应的列表......
list1.setCellRenderer(new InfoNameListCellRenderer());
请记住,模型数据的模型是模型,渲染器负责渲染数据。请勿更改模型以满足渲染要求。
请查看Concepts: Editors and Renderers和Writing a Custom Cell Renderer了解详情