简体   繁体   中英

Retrieving JLabel from JList

I have an instance of JList which contains JLabels with icons:

JList list = new JList();
list.setModel(model);
list.setCellRenderer(new DefaultListCellRenderer(){
     @Override
     public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        label.setIcon(icon);
        return label;
     }
  });

It works just fine, but I cannot figure out how programmatically I can retrieve this icon from the JLabel. I thought that maybe it's possible to do so with aid of model:

DefaultListModel model = list.getModel();

or cell renderer:

DefaultListCellRenderer model = list.getCellRenderer();

But yet none of them have the appropriate method for retrieving the label, not to mention the icon. I'm asking for your help: is it possible to get an icon from the line of the JList instance?

if you don't know how your list was rendered you have to re-render it on your own and retrive the icon...

int index = 0; //the index of the desired list entry
boolean isSelected = false; //icons my differ if they are selected
boolean cellHasFocus = false; //or have focus
Object value = list.getModel().getElementAt(index); //your 'string' or whatever is in your List
Component comp = list.getCellRenderer().getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (comp instanceof JLabel){
    JLabel pan = (JLabel) comp;
    Icon icon = pan.getIcon();

}

have an instance of JList which contains JLabels with icons:

You don't understand the concept of models and renderers.

You JList does not contains JLabels. The renderer of the JList is a JLabel which happens to display an Icon. You renderer is wrong because you are displaying the same Icon for every row in the list. This is not the way to use a JList.

Instead you add data to the ListModel of the JList. The default renderer for a JList is able to display String data or Icon data. So all you need to do is add an Icon to the model and the JList will display the Icon:

Icon[] items =
{
    new ImageIcon("copy16.gif"),
    new ImageIcon("about16.gif"),
    new ImageIcon("add16.gif")
};

JList<Icon> list = new JList<Icon>( items );

Then if you want to access the data for any given row in the list you can use:

Icon icon = list.getModel().getElementAt(...);

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