在JList中显示ImageIcon,该JList使用不同的Object来加载JList数据

时间:2011-07-30 17:59:15

标签: java swing jlist listcellrenderer imageicon

我有一个JList正在通过其他地方的字符串ArrayList填充,我想在同一个列表中现在显示一个保存在我的目录中的ImageIcon。现在我想为添加到列表中的任何项目(或列表中当前的任何项目)显示相同的图标。

我的列表应如下所示: ICON学生姓名...                                   图标学生姓名

问题(图像图标显示正确的高度并且正在捕获但在运行时未显示在列表中

这是我的动作监听器,它将数据添加到List。

 public class StudentListener implements ActionListener{

   private Main_Menu menu;
   private ArrayList<String> arrayList = new ArrayList<String>();;
   Iterator iterator = arrayList.iterator();
   JList sList;
   Map<Object, Icon> icons = new HashMap<Object, Icon>();        
   /**
    * 
    * @param menu the referenced menu from our main menu
    */
   public StudentListener(Main_Menu menu){
   this.menu = menu;       
   }

   @Override
    public void actionPerformed(ActionEvent ae) {

    Icon iCon = new ImageIcon("/Project/src/Images/1312046124_picture.png"); // icons
    int iHeight = iCon.getIconHeight();
       icons.put("name", iCon);           
      //add all the students to our List 
          try {
                StudentModel = new Student_Model();
            } catch (SQLException ex) {
                Logger.getLogger(Student_Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
    //arrayList = StudentModel.getStudents(); // modify to use an arrayList of string
    arrayList.add("John");
    arrayList.add("Smith");
    iterator = arrayList.iterator();
    while(iterator.hasNext()){          
       System.out.println(iterator.next().toString());
    }
    sList = this.menu.getStudentList();
    sList.setListData(arrayList.toArray());
    sList.setFont(new Font("Arial", Font.BOLD, 14));
    System.out.println("height of icon " + iHeight); // displays the correct height
    sList.setCellRenderer(new IconListRenderer(icons));       
   }   
  }

IconListCellRenderer

public class IconListRenderer
extends DefaultListCellRenderer {

private Map<Object, Icon> icons = null;

public IconListRenderer(Map<Object, Icon> icons) {
    this.icons = icons;
}

@Override
public Component getListCellRendererComponent(
    JList list, Object value, int index,
    boolean isSelected, boolean cellHasFocus) {

    // Get the renderer component from parent class

    JLabel label =
        (JLabel) super.getListCellRendererComponent(list,
            value, index, isSelected, cellHasFocus);

    // Get icon to use for the list item value

    Icon icon = icons.get(value);

    // Set icon to display for value

    label.setIcon(icon);
    return label;
}
  }

1 个答案:

答案 0 :(得分:1)

JList有方法如何将Icon / ImageIcon添加到ListCellRenderer,例如,链接大约是JComboBox,其中包含JList,另一个示例herehere