On my JFrame, I am using the following code to display an image on the Panel :
ImageIcon img= new ImageIcon(\"res.png\");
jLabel.setIcon(img);
Is there a way to set the size of the label
Override getPreferredSize()
of JLabel
and return the Dimension
s you want,
but because a JLabel
will size itself to its content you will just need to resize the picture you add to the JLabel
.
and then to autosize the image in the label?
You will have to resize your image according to the width and height you want (than simply add it to the JLabel
and the JLabel
will size to fit the image).
I do not recommend Image.getScaledInstance(..)
have a read here for more:
Image.getScaledInstance()
does not return a finished, scaled image. It leaves much of the scaling work for a later time when the image pixels are used.
Here is a custom method Ive been using to circumvent the issues created by getScaledInstance
:
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
you would create an image to whatever size you want via:
BufferedImage image=ImageIO.read(..);
BufferedImage resizedImage=resize(image,100,100);//resize the image to 100x100