Reputation: 175
I have a JList and i am using DefaultListModel,everything is well and the items(strings)are added correctly, but i want to add an image in JList beside each string (e.g.to show the status of the users).Can anyone help me about that? Thanks in advance.Here is how i add the elements,can i add images too?
private DefaultListModel modelO = (DefaultListModel) Teacher.made_list.getModel();
((DefaultListModel) Teacher.made_list.getModel()).addElement(studName);
Upvotes: 6
Views: 7787
Reputation: 830
Here you can find complex solution including
http://www.codejava.net/java-se/swing/jlist-custom-renderer-example
Upvotes: 0
Reputation: 27073
You have to implement ListCellRenderer (or extend DefaultListCellRenderer) and have the getListCellRendererComponent
method to return a Jlabel
with an icon in it.
Example:
public class IconListRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
Icon icon = this.getIcon(list, value, index, isSelected, cellHasFocus)
label.setIcon(icon);
return label;
}
protected Icon getIcon(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
// how do I get icon?
}
}
You have to implement the getIcon
method.
Upvotes: 7
Reputation: 3213
The model is used to store the data, and a renderer is used to display the data. The default renderer can handle Strings and icons but if you need to do more than that, you can provide a custom renderer. Here is an example. It's for a combo box, but the renderer is the same for JLists.
Upvotes: 3