1
我有一個JList通過其他地方的字符串的ArrayList填充,我想要爲同一列表現在顯示保存在我的目錄中的ImageIcon某處。現在我想爲添加到列表中的任何項目(或當前列表中的任何項目)顯示相同的圖標。在使用不同對象的JList中顯示ImageIcon來加載JList數據
我的目錄應該是這樣的:圖標學生姓名... 圖標學生姓名
問題(圖像圖標顯示正確的高度,它被捕獲,但在列表中不顯示運行時
下面是添加數據的列表我的動作監聽。
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;
}
}
你還沒有發佈的SSCCE!我們無法訪問您的StuentModel或IconListRenderer。我們甚至不需要SSCCE的StudentModel。你所需要做的就是在你的ArrayList中硬編碼一些學生的名字。我猜這個問題是渲染器。 **如果您需要幫助**,請發佈正確的SSCCE。每當您發佈問題時,我都厭倦了提醒您。 – camickr
我必須同意camickr:沒有辦法,我們可以猜測爲什麼你的代碼不工作沒有一個小的工作例子。如果你希望提供一個SSCCE,你真的取決於你 - 你需要多少幫助? –
@Camickr,不需要動畫,我真的很接近解決這個問題,也許我只是沒有正確使用ListCellRenderer屬性,這就是爲什麼我發佈了引用代碼。我會更新我的帖子以獲得更好的回覆。 – Warz