简体   繁体   中英

Add an image to a JList item

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 (egto 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 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.

Here you can find complex solution including

  • Custom JList elements (that allows to get icon image from list element)
  • Handling selection styling
  • More convinient way of using ListCellRenderer than just extending Default

http://www.codejava.net/java-se/swing/jlist-custom-renderer-example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM