1

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

我的列表应该如下所示:ICON STUDENT NAME ... ICON STUDENT NAME

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

这是我将数据添加到列表的操作侦听器。

 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;
}
  }
4

1 回答 1

1

JList具有如何将 Icon/ImageIcon 添加到ListCellRenderer的方法,例如链接是关于包含的JComboBox ,此处此处JList的另一个示例

于 2011-07-30T18:12:11.267 回答