在jlist中添加图片

时间:2013-04-05 14:48:07

标签: java swing applet jlist

我正在使用java中的applet编写一个简单的基于文本的聊天应用程序,该应用程序包含少量组件和其中一个是我的Jlist,它提供了特定时间点的在线用户列表。

我想要的是我需要在Jlist中设置除在线用户名之外的小图片。

有没有人基于此有任何想法。如果您有任何问题,请随时询问。

谢谢, 普纳特

1 个答案:

答案 0 :(得分:0)

JList文档中有一个将图标加载到JList中的示例。您应该可以使用它将小图片插入JList。

http://docs.oracle.com/javase/6/docs/api/javax/swing/JList.html

以下是该链接的相关代码:

  // Display an icon and a string for each object in the list.

 class MyCellRenderer extends JLabel implements ListCellRenderer {
     final static ImageIcon longIcon = new ImageIcon("long.gif");
     final static ImageIcon shortIcon = new ImageIcon("short.gif");

     // This is the only method defined by ListCellRenderer.
     // We just reconfigure the JLabel each time we're called.

     public Component getListCellRendererComponent(
       JList list,              // the list
       Object value,            // value to display
       int index,               // cell index
       boolean isSelected,      // is the cell selected
       boolean cellHasFocus)    // does the cell have focus
     {
         String s = value.toString();
         setText(s);
         setIcon((s.length() > 10) ? longIcon : shortIcon);
         if (isSelected) {
             setBackground(list.getSelectionBackground());
             setForeground(list.getSelectionForeground());
         } else {
             setBackground(list.getBackground());
             setForeground(list.getForeground());
         }
         setEnabled(list.isEnabled());
         setFont(list.getFont());
         setOpaque(true);
         return this;
     }
 }

 myList.setCellRenderer(new MyCellRenderer());

假设您的JList包含用户名,您可以将您的用户名放在HashMap中

setIcon(userHashMap.get(s));

如果您的JLIst实际上存储的不仅仅是用户名(动态组件,如状态,组名等),那么您可能需要从传递给值对象的String中解析出用户名。