Question

I am writing a custom jlist cell renderer for some kind of filechooser. My problem is that when I read my ImageIcon, it seems it has the dimension (-1,-1), so I can't resize it properly. The picture is a simple texture (wood, metal, etc.). Then I thought that if I added a JPanel instead of an image, and then adding the image to the panel, I wouldnt even have to resize the picture.

I have 2 possibilities:

  1. Read the ImageIcon from the hard drive so that they dont have dimension -1,-1
  2. Insert a JPanel inside the JLabel.

Here is a preview of my list cells.

enter image description here

Here is my custom renderer, which adds icons to the cells.

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;
    }
}
Was it helpful?

Solution

Just replace the label with the panel.

You can use a JPanel as the rendercomponent instead of the JLabel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top