我正在为某种文件选择器编写自定义 jlist 单元格渲染器。我的问题是,当我读取我的 ImageIcon 时,它似乎具有尺寸 (-1,-1),所以我无法正确调整它的大小。图片是简单的纹理(木头,金属等)。 然后我想如果我添加一个 JPanel 而不是图像,然后将图像添加到面板,我什至不必调整图片的大小。
我有两种可能性:
- 从硬盘读取 ImageIcon,使它们不具有维度 -1,-1
- 在 JLabel 中插入一个 JPanel。
这是我的列表单元格的预览。
这是我的自定义渲染器,它向单元格添加图标。
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);
ImageIcon icon = (ImageIcon)icons.get(value);
// Set icon to display for value
label.setIcon(icon);
label.setText(value.toString());
return label;
}
}
最佳答案
只需将标签替换为面板即可。
您可以使用 JPanel
作为渲染组件而不是 JLabel
。
关于java - 如何在 JLabel 中插入 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9617443/