Mam klasę ChannelData, w której mam pola String. Tworzę JList:
JList<ChannelData> channelList = new JList<>(listModel);
owner.add(new JScrollPane(channelList));
channelList.setCellRenderer(new Renderer());
owner.setVisible(true);
public class Renderer extends JLabel implements ListCellRenderer<ChannelData>
{
public Renderer()
{
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList<? extends ChannelData> list, ChannelData channel, int index,
boolean isSelected, boolean cellHasFocus) {
String name = channel.getAName().trim();
name = name.replace(" ", "");
name = name.toLowerCase();
ImageIcon imageIcon;
File f = new File("./images/" + name + ".png");
if (f.exists())
imageIcon = new ImageIcon("./images/" + name + ".png");
else
imageIcon = new ImageIcon(getClass().getResource("app.png"));
imageIcon = scaleImage(imageIcon,50,30);
setIcon(imageIcon);
setText(channel.getAName());
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setBorder(BorderFactory.createMatteBorder(2, 0, 2, 0,Color.BLUE));
return this;
}
private ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
}
Czy można dodawać elementy do JList w osobnym wątku. Być może dałoby się zrobić, aby najperw pojawiły się nazwy, a po skończenu w osobny wątku dodawane by były ikony?