开发者

Custom JLabel icon

I want to use java JLabel with an Icon in custom size on my GUI. like this :

Custom JLabel icon

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_B开发者_如何学PythonILINEAR);

    g2.drawImage(srcImg, 0, 0, w, h, null);

    g2.dispose();
    return resizedImg;
}    

but after resizing image and using this code the result is this! :

Custom JLabel icon

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜