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; } @Override protected void paintComponent(Graphics g) { Dimension size = getSize(); if (imageToDisplay!=null && size.width>0) { g.drawImage(imageToDisplay, 0, 0, size.width, size.height, 0, 0, imageToDisplay.getWidth(null), imageToDisplay.getHeight(null), null); } } }
Array ( ) One Response to “How do I display an image that resizes according to the size of the panel?”
Leave a Reply
You must be logged in to post a comment.
September 15th, 2009 at 7:04 pm
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.