How to add label icon in to our Swing Jlist box
----------------------------------------------------
Steps.
-----
1.create a class(here OnlineUserCellRenderer) and implement ListCellRenderer.
class OnlineUserCellRenderer extends JLabel implements
ListCellRenderer {
private final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public OnlineUserCellRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
TestImageList entry = (TestImageList) value;
setText(entry.getUser());
if (entry.getImage() != null) {
setIcon(entry.getImage());
}
setIconTextGap(12);
if (isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
}
private final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public OnlineUserCellRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
TestImageList entry = (TestImageList) value;
setText(entry.getUser());
if (entry.getImage() != null) {
setIcon(entry.getImage());
}
setIconTextGap(12);
if (isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
}
2. Then create a TestImageList class.This class is used to set
properties for label.
class TestImageList {
private final String Name;
private ImageIcon image;
public TestImageList(String Name, ImageIcon image) {
this.Name = Name;
this.image = image;
}
public String getName() {
return Name;
}
public ImageIcon getImage() {
return image;
}
// Override standard toString method to give a useful result
public String toString() {
return Name;
}
}
private final String Name;
private ImageIcon image;
public TestImageList(String Name, ImageIcon image) {
this.Name = Name;
this.image = image;
}
public String getName() {
return Name;
}
public ImageIcon getImage() {
return image;
}
// Override standard toString method to give a useful result
public String toString() {
return Name;
}
}
3. Declare DefaultListModel object for inserting data in to jlist
box in our class import javax.swing.DefaultListModel.and
declare a object for DefaultListModel.
public DefaultListModel model = new DefaultListModel();
4. Then add elements in to our DefaultListModel for insert it in
to swing jList box.
model.add(comboCount, new OnlineUserListEntry(Name, newIcon));
lstChatlist.setModel(model);
OnlineUserCellRenderer labelUser = new OnlineUserCellRenderer();
lstChatlist.setCellRenderer(labelName);
lstChatlist.setModel(model);
OnlineUserCellRenderer labelUser = new OnlineUserCellRenderer();
lstChatlist.setCellRenderer(labelName);