How do I embed a JPanel inside a JLabel?

I am writing a custom jlist cell rendering for a kind of filechooser. My problem is when I read my ImageIcon it seems to have a size (-1, -1) so I cannot change it. The image is a simple texture (wood, metal, etc.). Then I thought that if I add a JPanel instead of an image and then add an image to the panel, I don't even have to resize the image.

I have 2 possibilities:

  • Read ImageIcon from hard drive so they don't have dimension -1, -1
  • Paste JPanel inside JLabel.

Here is a list of my list cells.

enter image description here

Here is my custom renderer that adds icons to 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;
    }
}

      

+3


source to share


1 answer


Just replace the shortcut to the panel.



You can use JPanel

render instead of JLabel

.

+3


source







All Articles