tpm900 tpm900 - 1 year ago 151
Java Question

Width and Height must be non-zero when scaling image for JPanel

I am trying to scale an image to fit within a JPanel in my GUI. Whenever I create a new instance of

in my JFrame, I get an exception because the width and the height are both 0. However, I overrode
so it seems like the width and height should be non-zero values.

public class ImagePanel extends JPanel {

private Image image;

public ImagePanel() {
try {
image = File("resources/opening.jpg"));
image = scaleImage(image);
} catch (IOException e) {

public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);

public void setImage(Image i) {
image = scaleImage(i);

public Dimension getPreferredSize() {
return new Dimension(500, 500);

public Image scaleImage(Image i) {
return i.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);

Here is the stack trace:

Exception in thread "main" java.lang.IllegalArgumentException: Width (0) and height (0) must be non-zero
at java.awt.image.ReplicateScaleFilter.<init>(
at java.awt.image.AreaAveragingScaleFilter.<init>(
at java.awt.Image.getScaledInstance(
at ImagePanel.scaleImage(
at ImagePanel.<init>(
at GUIFrame.<init>(
at main.main(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at com.intellij.rt.execution.application.AppMain.main(

Answer Source

A component doesn't have a size until the panel is displayed in a visible GUI.

So the solution is to do the scaling of your image dynamically in the paintComponent(...) method.

Note you can do this with the drawImage(...) method directly. Read the API there is a method that allows you to specify the width/height of the image as you paint the image.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download