The easy/naive way to scale the image to fill the component, viz, your contentPane, is to scale the width and height of the image to the respective width and height of the component.
In java:
double xScale = (double)componentWidth/imageWidth;
double yScale = (double)componentHeight/imageHeight;
int width = (int)(xScale*imageWidth);
int height = (int)(yScale*imageHeight);
This will distort the image when the component and image have differing aspect ratios (w/h). This may be exactly what you want.
In case it is not what you want we have two possibilities to consider:
1 —
scale to fit in which the image is scaled so that it just fits into the component. This will usually leave some of the component background showing, ie, not all of the component is covered by the image.
2 —
scale to fill where the image completely fills the component background. If the image and component have different aspect ratios (w/h) then some of the image will not show, ie, the scaled image will be larger than the component size.
Here is a test app demonstrating these last two options. Drag the sides of the frame to test the resizing behavior.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class AutoResize extends JPanel {
BufferedImage image;
public AutoResize(BufferedImage image) {
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
int w = getWidth();
int h = getHeight();
int iw = image.getWidth();
int ih = image.getHeight();
double xScale = (double)w/iw;
double yScale = (double)h/ih;
double scale = Math.min(xScale, yScale); // scale to fit
//Math.max(xScale, yScale); // scale to fill
int width = (int)(scale*iw);
int height = (int)(scale*ih);
int x = (w - width)/2;
int y = (h - height)/2;
g2.drawImage(image, x, y, width, height, this);
}
public static void main(String[] args) throws IOException {
String path = "images/bison.jpg";
BufferedImage image = ImageIO.read(new File(path));
AutoResize test = new AutoResize(image);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
Another way to do this is to make a BufferedImage (the size of the contentPane) and scale the source image into it and draw this new BufferedImage into your contentPane. Add a ComponentListener to the contentPane and make a new BufferedImage for each
componentResized event.
About the loading method: ImageIo is the newest way to load images, since j2se 1.4. ImageIcon is an older way, since j2se 1.2. ImageIcon is easy but uses MediaTracker to load images and this does no let you know (without extra work) if the image file can not be found of if the image data is corrupted, unreadable or cannot be loaded. ImageIO does let you know.