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);
You have to supply to the JLabel an Icon implementation (i.e ImageIcon ). You can do it trough the setIcon method, as in your question, or through the JLabel constructor: Image image=GenerateImage. toImage(true); //this generates an image file ImageIcon icon = new ImageIcon(image); JLabel thumb = new JLabel(); thumb.
JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With