I have a JPanel to which I'd like to add JPEG and PNG images that I generate on the fly.
All the examples I've seen so far in the Swing Tutorials, specially in the Swing examples use ImageIcon
s.
I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.
Edit: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...
To add an image to JPanel, the Java Swing framework provides built-in classes such as ImageIO and ImageIcon that you can use to fetch an image.
Adding an Image in Java JFrame Firstly, we create a JLabel using the Java Swing library. Secondly, we use the setIcon() method to add and display the image. This method defines to display the icon.
If you are using JPanels, then are probably working with Swing. Try this:
BufferedImage myPicture = ImageIO.read(new File("path-to-file")); JLabel picLabel = new JLabel(new ImageIcon(myPicture)); add(picLabel);
The image is now a swing component. It becomes subject to layout conditions like any other component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With