Sep 23

You can create a JPanel subclass that uses the size of the panel to determine what size to paint the image. The image can then be painted in the (overridden) paintComponent() method at the required size.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScaledImagePanel extends JPanel
   private Image imageToDisplay = null;

   public void setImageToDisplay(Image imageToDisplay)
      this.imageToDisplay = imageToDisplay;

   protected void paintComponent(Graphics g)
      Dimension size = getSize();
      if (imageToDisplay!=null && size.width>0)
            0, 0, size.width, size.height, 
            0, 0, imageToDisplay.getWidth(null), 

written by objects \\ tags: ,

Array ( ) One Response to “How do I display an image that resizes according to the size of the panel?”

  1. Royce Warren Says:

    Thank you so very much for your time and effort. As a java student, I find this organization to be fantastic and worth every penny. I will be back. Thank you.

Leave a Reply

You must be logged in to post a comment.