Reputation: 856
I have JPanel Which will load images.
Since images will not have the same width and height as the JPanel, I want to make the image resize and fit in the JPanel.
Upvotes: 5
Views: 38910
Reputation: 12092
Read on this article, The Perils of Image.getScaledInstance()
Now IF you STILL prefer you can use something like,
Image scaledImage = originalImage.getScaledInstance(jPanel.getWidth(),jPanel.getHeight(),Image.SCALE_SMOOTH);
this before loading the image to your JPanel, probably like discussed in this answer.
Upvotes: 12
Reputation: 1001
I know this is quite old, but maybe this helps other people
use this class instead of a normal JLabel and pass an ImageIcon when using setIcon(#);
private class ImageLabel extends JLabel{
private Image _myimage;
public ImageLabel(String text){
super(text);
}
public void setIcon(Icon icon) {
super.setIcon(icon);
if (icon instanceof ImageIcon)
{
_myimage = ((ImageIcon) icon).getImage();
}
}
@Override
public void paint(Graphics g){
g.drawImage(_myimage, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
Upvotes: 7