ninabei
ninabei

Reputation: 65

Java Fill image into Label

I have a fixed size label to display image. How do I have the image resized to fit into the label, filled up. My current code below, is setting the label to the image size, I want it the other way round.

Code

ImageIcon icon = new ImageIcon(bi);
Label.setIcon(icon);
Dimension imageSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
Label.setPreferredSize(imageSize);
Label.revalidate();
Label.repaint();

Upvotes: 2

Views: 1930

Answers (2)

camickr
camickr

Reputation: 324197

You can use Darryl's Stretch Icon. The Icon will resize based on the space available to the label.

Upvotes: 2

So if you have a fixed size label, you can simple read image as BufferedImage object and then scale it to size of your label. After that you can create an icon and set it as JLabel's icon. Below code should work:

File imageFile = new File("image.jpg");
BufferedImage bufImg = null;

try {
    bufImg = ImageIO.read(imageFile);
} catch (IOException e) {
    e.printStackTrace();
}

BufferedImage scaledImg = bufImg.getScaledInstance(Label.width, Label.height, Image.SCALE_SMOOTH);

Label.setIcon(new ImageIcon(scaledImg));

Upvotes: 0

Related Questions