Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an image to a JList item

Tags:

java

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);
like image 617
Fatema Mohsen Avatar asked Apr 27 '11 16:04

Fatema Mohsen


People also ask

How do I add a JLabel to a photo?

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.

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.


2 Answers

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.

like image 55
Lesmana Avatar answered Oct 03 '22 19:10

Lesmana


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.

like image 32
z7sg Ѫ Avatar answered Oct 03 '22 21:10

z7sg Ѫ