I want to draw a jpg image in a JFrame, so I used JPEGImageDecoder and read
it into a BufferedImage, which I draw to a JPanel.
But when I add the component (JPanel) to the JFrame, pack() doesn't work,
and I have to setSize() explicitly.
Why doesn't pack() work? I can't do imagePanel.getWidth() either, it's 0
until visible.
(Oh, I should mention, pack() still doesn't work after it's visible...do I
have to wait
until the image is rendered?)
Also, what's the best way to swap images dynamically in this case?
TIA
Jeff
////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
public class MyImagePanel {
static String filename = "picture.jpg";
public static void main(String[] args) {
JFrame frame = new JFrame("MyImagePanel");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
MyImagePanel panel = new MyImagePanel();
ImagePanel imagePanel = new ImagePanel(filename);
frame.getContentPane().add(imagePanel, BorderLayout.CENTER);
frame.setSize((int)imagePanel.image.getWidth()+8,(int)imagePanel.image.getHe
ight()+22);
frame.setLocation(100, 100);
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
BufferedImage image;
public ImagePanel(String filename) {
try {
InputStream in = getClass().getResourceAsStream(filename);
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
image = decoder.decodeAsBufferedImage();
in.close();
// System.out.println((int)image.getWidth());
// System.out.println((int)image.getHeight());
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
Knute Johnson - 03 Nov 2003 16:53 GMT
> I want to draw a jpg image in a JFrame, so I used JPEGImageDecoder and read
> it into a BufferedImage, which I draw to a JPanel.
[quoted text clipped - 59 lines]
> }
> }
This is one of those chicken and egg things. The layout manager doesn't
know how big your JPanel needs to be so it shrinks it to minimum size.
There are a couple of things that you need to do. First you need to
find out the size of your image (which you already do). Next you need
to override getPreferredSize() in your JPanel and have it return the
size of your image. Then pack() will know how big it is supposed to be.

Signature
Knute Johnson
email s/nospam/knute/
Molon labe...