0

我的图像就像一个中间透明的框架。我想将其作为 JPanel 的背景图像。我已经这样做了,但是对于图像的透明部分,白色即将到来。我想删除这个白色,以便这个 Jpanel 下面的组件变得可见。

我的自定义 JPanel 代码是

public class JPanelWithBackground extends JPanel {
private static final long serialVersionUID = 1L;
Image imageOrg = null;
Image image = null;
{
     addComponentListener(new ComponentAdapter() {
             public void componentResized(ComponentEvent e) {
             int w = JPanelWithBackground.this.getWidth();
             int h = JPanelWithBackground.this.getHeight();
             image = w>0&&h>0?imageOrg.getScaledInstance(w,h, 
             java.awt.Image.SCALE_SMOOTH):imageOrg;
             JPanelWithBackground.this.repaint();
   });
 }
 public JPanelWithBackground(Image image2) {
    imageOrg=image2;
    image=image2;
    setOpaque(false);
    }
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image!=null) 
      g.drawImage(image, 0, 0, null);
   }
}
4

1 回答 1

3

我对您的代码没有任何特别的问题。问题可能是您的图像不像您期望的那样透明。

这是一个似乎可以完美运行的示例(我只是冒昧地修复了您代码中的小问题):

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JPanelWithBackground extends JPanel {
    private static final long serialVersionUID = 1L;
    Image imageOrg = null;

    public JPanelWithBackground(Image image2) {
        imageOrg = image2;
        setOpaque(false);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(imageOrg.getWidth(this), imageOrg.getHeight(this));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (imageOrg != null) {
            System.err.println("painting");
            g.drawImage(imageOrg, 0, 0, getWidth(), getHeight(), this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JPanelWithBackground panel = new JPanelWithBackground(new ImageIcon(new URL(
                            "http://www.lemondedemario.fr/images/dossier/bowser/bowser.png")).getImage());
                    JPanel greenPanel = new JPanel(new BorderLayout());
                    greenPanel.setBackground(Color.GREEN);
                    greenPanel.add(panel);
                    frame.add(greenPanel);
                    frame.pack();
                    frame.setVisible(true);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}
于 2013-04-16T13:25:22.290 回答