简体   繁体   English

如何使JFrame背景图像透明?

[英]How to make JFrame background image transparent?

Currently, I'm using this code to generate a background image for my JFrame: 目前,我正在使用此代码为我的JFrame生成背景图片:

    BufferedImage myImg = ImageIO.read(myUrl);
    this.setContentPane(new ImagePanel(myImg));

    //ImagePanel class
    public class ImagePanel extends JComponent {
        private Image image;
        public ImagePanel(Image image) {
            this.image = image;
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }

As a result of this, the image covers up everything that I have in the JFrame. 因此,图像覆盖了我在JFrame中拥有的所有内容。 How can I toggle the transparency of the image being drawn so that I can still see my content while having the image set as the background? 如何切换正在绘制的图像的透明度,以便在将图像设置为背景时仍能看到我的内容?

protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, null);

Should be: 应该:

protected void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint the parent component!
        g.drawImage(image, 0, 0, this);

EG 例如

  1. Answer to Drawing a background image. 回答绘制背景图像。
  2. Answer to Background image hides all GUI design components. 背景图像的回答隐藏了所有GUI设计组件。

Why do you keep talking about transparency? 为什么一直谈论透明度? You would only care about transparency if you are painting an image "on top" of your components. 如果要在组件的“顶部”上绘制图像,则只关心透明度。

If you want a background image on your frame then you add the image to a panel and add the panel to the frame. 如果要在框架上显示背景图像,则将图像添加到面板并将面板添加到框架中。 Then you add other components to the background panel so that those components are displayed on top of the image. 然后将其他组件添加到背景面板,以便这些组件显示在图像的顶部。

This has nothing to do with transparency. 这与透明度无关。

The background panel is generally a JPanel, not a JComponent since a panel is designed to be used as a container. 后台面板通常是JPanel,而不是JComponent,因为面板设计用作容器。

See Background Panel for an example. 有关示例,请参见背景面板

You can't just change an image to make it transparent. 您不能只是更改图像以使其透明。 You need to load an image with transparent pixels. 您需要加载带有透明像素的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM