3

我正在为某种文件选择器编写自定义 jlist 单元格渲染器。我的问题是,当我阅读我的 ImageIcon 时,它似乎具有尺寸(-1,-1),所以我无法正确调整它的大小。图片是简单的纹理(木头、金属等)。然后我想如果我添加一个JPanel而不是图像,然后将图像添加到面板中,我什至不必调整图片大小。

我有两种可能性:

  1. 从硬盘读取 ImageIcon,使它们没有尺寸 -1,-1
  2. 在 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;
    }
}
4

1 回答 1

4

只需将标签替换为面板即可。

您可以使用 aJPanel作为渲染组件而不是JLabel.

于 2012-03-08T12:29:28.677 回答