我想添加一些图像到我的jlist。下面的代码工作得很好
public class MarioList {
private final Map<String, ImageIcon> imageMap;
public MarioList() {
String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
try {
map.put("Mario", new ImageIcon(new URL("https://i.stack.imgur.com/NCsHu.png")));
map.put("Luigi", new ImageIcon(new URL("https://i.stack.imgur.com/UvHN4.png")));
map.put("Bowser", new ImageIcon(new URL("https://i.stack.imgur.com/s89ON.png")));
map.put("Koopa", new ImageIcon(new URL("https://i.stack.imgur.com/QEK2o.png")));
map.put("Princess", new ImageIcon(new URL("https://i.stack.imgur.com/f4T4l.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MarioList();
}
});
}
}
上面的代码创建了一个新框架,并在其中添加了一个jscrollpane。相反,我尝试使用Netbeans手动创建框架和jcrollpane。所以不用这段代码;
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
我使用了这个代码;
jList1.add(nameList);
jList1.setCellRenderer(new MarioListRenderer());
这里jList1是我通过Netbeans创建的jlist,它被放在jscrollpane中。但是这个代码不起作用。请告诉我得到这份工作的方法……谢谢你
假设您正在使用Java 7+…
jList1.add(nameList);
应该jList1.setListData(nameList);
否则,您将需要将nameList
包装在ListModel
实现中