不要JList
用String
数组实例化 a ,而是用您选择的对象数组实例化它。确保您覆盖该toString
方法,因为这就是将要绘制的内容。例如:
public class Item {
private int id;
private String name;
public Item(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
如果Item
是数据模型的一部分,则将其添加到 JList 模型中,如下所示:
public class AppJList extends JFrame {
public AppJList() {
super("JList model test");
initUI();
}
public Item[] initModel() {
Item[] model = new Item[3];
for (int i = 0; i < model.length; i++) {
model[i] = new Item(i, "text " + i);
System.out.println(i);
}
return model;
}
public JPanel initMainPanel() {
JPanel jpanel = new JPanel();
JList jList = new JList(initModel());
jList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList list = ((JList) e.getSource());
Item selected = (Item) list.getModel().getElementAt(list.getSelectedIndex());
System.out.println("selected item with id: " + selected.getId());
}
}
});
jpanel.add(jList);
return jpanel;
}
public void initUI() {
this.setPreferredSize(new Dimension(200, 200));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(new JScrollPane(initMainPanel()));
this.setLocationByPlatform(true);
this.pack();
}
public static void main(String[] args) {
// SwingUtilities.invokeLater
// or
EventQueue.invokeLater(new Runnable() {
public void run() {
new AppJList().setVisible(true);;
}
});
}
}
如果您想更好地控制列表呈现,请添加自定义ListCellRenderer:
jList.setCellRenderer(new ListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Item toBeRendered = (Item)list.getModel().getElementAt(index);
return new JLabel(toBeRendered.getId() +":"+toBeRendered.getName());
}
});
在initMainPanel
方法中。有关详细说明,请查看以下教程: