3

我有一个图像(gif 或 png),其中一些透明部分在放入 JLabel 时显示为黑色。

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

我该如何解决这个问题?

我不需要 JLabel,也许有更好的方法可以直接在 JPanel 上正确显示图像(即具有透明度)?

谢谢大卫

4

2 回答 2

10

找到了罪魁祸首!

实际上,图片在添加到 JLabel 之前已经重新缩放,为此,我使用了 BufferedImage.TYPE_INT_RGB 而不是 BufferedImage.TYPE_INT_ARGB

我真的不认为重新缩放方法可以改变这一点(我傻了!),这就是为什么我没有在我添加到问题的代码中显示它......

大卫

于 2011-01-14T18:05:17.713 回答
3

同样,您确定这是 JLabel 的错吗?当我尝试做一个概念验证程序时,一切正常——背景JPanel 的粉红色被看到了。例如,

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();
            }
        });
    }
}

您可能希望自己创建一个类似的程序来查看您的问题是否以及在哪里,然后将其发布在这里。

于 2011-01-14T17:55:43.513 回答