Custom JLabel icon
I want to use java JLabel with an Icon in custom size on my GUI. like this :
I used this code to change size of original Icon :
ImageIcon imageIcon = (ImageIcon) jLabel1.getIcon();// new ImageIcon( "Play-Hot-icon.png");
ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(imageIcon.getImage(), 25 , 25));
jLabel1.setIcon(thumbnailIcon);
and here is code for resize image
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
but after resizing image and using this code the result is this! :
how can I have desired image on my JLabel??
regards, sajad
The problem is that when you create the scaled image, you use BufferedImage.TYPE_INT_RGB
for your new image, and transparency gets rendered as black with just TYPE_INT_RGB
.
In order to keep transparency, you need to replace that with BufferedImage.TYPE_INT_ARGB
, since you need an alpha component.
However, calling Image.getScaledInstance on imageIcon
's image will return a scaled image, already with an alpha component, and you can pass it rendering hints to play with the quality of the scaled image, doing essentially the same as your getScaledImage
function, but with less of the hassle.
下一篇: 自定义JLabel图标