开发者

transparent parts of GIF/PNG image shown in black inside a JLabel java

I have an image (gif or png) with some transparents parts which appear in black when put inside a JLabel.

    ClassLoader cl = this.getClass().getClassLoader();
    ImageIcon img = new ImageIcon(cl.getResource("resources/myPicture.png"));
    label = new JLabel(img);

How do I work开发者_运维知识库 around this problem ?

I do not need the JLabel, maybe there is a better way to display the image correctly (i.e. with the transparency) directly on a JPanel ?

Thanks David


Found the culprit !

Actually the picture is getting rescaled before being added to the JLabel and for that, I used BufferedImage.TYPE_INT_RGB instead of BufferedImage.TYPE_INT_ARGB

I really didn't think that the rescaling method could alter this (silly me!), that's why I didn't show it in the code I added to the question...

David


Again, are you sure that it's the JLabel's fault? When I tried to do a proof of concept program, everything worked fine -- the background JPanel's pink color was seen. e.g.,

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TransparentJLabel {
    private static final String IMAGE_PATH = "http://duke.kenai.com/Oracle/OracleStratSmall.png";

    private static void createAndShowUI() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.pink);

        URL imageUrl;
        try {
            imageUrl = new URL(IMAGE_PATH);
            BufferedImage image = ImageIO.read(imageUrl);
            ImageIcon icon = new ImageIcon(image);
            JLabel label = new JLabel(icon);
            panel.add(label);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        JFrame frame = new JFrame("TransparentJLabel");
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

You may wish to create a similar program yourself to see if and where your problem is, and then post it here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜