5

Is there any better way to get the Icon of a JLabel in a container as a BufferedImage whithout multiple casts?

Component[] components = container.getComponents();
BufferedImage image = ((BufferedImage) ((ImageIcon) ((JLabel) components[i]).getIcon()).getImage());
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sp0tlight
  • 409
  • 1
  • 4
  • 18
  • 5
    Yes, use reference variables rather than the potentially dangerous `getComponents()`. i.e., `myLabel.getIcon().getImage()`. – Hovercraft Full Of Eels Jun 29 '13 at 20:22
  • Hmm, I don't think I can use any references. I need the image inside the `layoutContainer(Container container)` method implemented by my layoutManager to scale it proportional to the rest of the gui. – Sp0tlight Jun 29 '13 at 20:31
  • We've got a case of shifting requirements. Consider telling us more information, enough so that we can fully understand and answer your question. Please have a look here: [Jon Skeet: Writing the Perfect Question](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx). – Hovercraft Full Of Eels Jun 29 '13 at 20:36
  • I'd like to implement a custom layout manager for my gui. In the `layoutContainer(Container container)` method I have to scale each component. Some of my JLabels containing a image so i need to scale the images as well. I just wonder if i could avoid this many casts or rather find another method for scaling images inside a JLabel. – Sp0tlight Jun 29 '13 at 20:52
  • 3
    @Sp0tlight Thats not the responsibility of the layut manager (to scale the images), that's the responsibility of the component – MadProgrammer Jun 29 '13 at 21:35
  • Should I therefore create a subclass of JLabel and implement a scaleImage method that i call in my LayoutManager? i.e. `if(comp instanceof MySuclass)comp.scaleImage();` – Sp0tlight Jun 29 '13 at 21:58
  • I would probably go for subclassing ImageIcon to do the scaling (the label has not much business in second-guessing the painting of its icon) Curious: why do you need to scale in the first place? Would it be an option to leave the ui/layout alone and do the transform in a LayerUI? – kleopatra Jun 30 '13 at 09:57
  • I have to create a resolution dependent gui, where also the images must scale proportional to the viewport size of the users. Do you mean, that i should display the images in a LayerUI instead of adding them to a JLabel inside a JPanel? – Sp0tlight Jun 30 '13 at 14:27

1 Answers1

2

In order to get a buffered image from a JLabel, you do the following (which is what your original answer asked):

Icon icon = label.getIcon();
BufferedImage bi = new BufferedImage(icon.getIconWidth(),
                icon.getIconHeight(),BufferedImage.TYPE_INT_RGB);
nook
  • 2,378
  • 5
  • 34
  • 54