Java小程序,让背景透明

Java Applet, make the background transparent

我在 YouTube 上看了一个关于如何在 Java 中显示图像的教程,他使用了一种叫做 "Applet" 和 "Graphics" 的东西来显示它,我知道了工作,我很高兴。现在我打算在屏幕中央制作一个 chrome 徽标,透明且没有背景,然后 chrome 打开。你知道,我已经给 class CustomChrome 打电话了。习俗之类的。每当我开始 chrome 时,我只想要一个很酷的开场白。

这是当前代码:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

public class CustomChrome extends Applet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Image logo = null;

    public void paint(Graphics g) {

        this.setSize(960, 540);

        if (logo == null)
            logo = getImage("/chromelgo.png");

        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(logo, 0, 0, 960, 540, this);
    }

    public Image getImage(String path) {

        Image tempImage = null;
        try {

            URL imageURL = CustomChrome.class.getResource(path);
            tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
        } catch (Exception e) {

            System.out.println("An error occured - " + e.getMessage());

        }

        return tempImage;
    }


}

然而,我想要做的是使背景 + window 消失,完成后我会将图像和 window 大小设置为 1920x1080。我该如何继续使图像后面的 window 消失?我听说过有关实现 ActionListener 的一些信息,但我仍然不确定该怎么做。

切记!我没有使用 java 的经验,如果您试图帮助我,很抱歉让您不高兴 :P

好的,让我们从真正明显的问题开始,小程序实际上已被弃用,您应该停止使用它们,有关详细信息,请参阅 Java Plugin support deprecated and Moving to a Plugin-Free Web

paintXxx 用于绘画,你永远不应该在绘画方法中改变组件的状态(你也不应该在小程序中调用 setSize)。请参阅 Painting in AWT and Swing and Performing Custom Painting 了解有关绘画如何工作以及如何使用它的更多详细信息

作为一般性建议,我建议 ImageIO.read 而不是 Toolkit#getImageImageIcon 来加载图像,除了在图像可以加载时抛出 Exception未被读取(而不是静默失败),它也是一个阻塞调用,这意味着当它 returns 时,图像已完全加载。

有关详细信息,请参阅 Reading/Loading an Image

一句警告 - 你想要做的事情本身并不难,但它涉及并需要一定的关于 API 工作原理的大量知识。

Now what I was planning to make is a chrome logo in the center of my screen, transparent with no background, and then chrome opens.

好吧,这永远不会与小程序一起使用,因为小程序旨在显示在浏览器中,因此您无法控制 window,相反,您需要类似 JFrame,参见 How to Make Frames (Main Windows)

What I want to do, however, is the make the background + the window to vanish, Once that's was done I will set the image and window size to 1920x1080. How do I go forward on making the window behind the image disappear?

现在,这才是真正有趣的开始。您会想先看看 How to Create Translucent and Shaped Windows。这将允许您控制框架的不透明度,使其消失,但允许内容保留,您需要做一些技巧才能将其拉下来,但这是基本思想

因此,此示例将创建一个透明 window 并在其中居中显示和图像。

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage img = ImageIO.read(getClass().getResource("/Chrome.png"));
                    ImageIcon icon= new ImageIcon(img);
                    JLabel label = new JLabel(icon);

                    JFrame frame = new JFrame("Testing");
                    frame.setUndecorated(true);
                    frame.setBackground(new Color(0, 0, 0, 0));
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}

在这个例子中,我使用 JLabel 来显示图像,在大多数情况下,这就是您真正需要的,详情请参阅 How to Use Labels

What I want to do, however, is the make the background + the window to vanish

好吧,归结为你所说的消失是什么意思。您可以只在 window 上使用所有 disposesetVisible,这会关闭它,所有您都可以使用一些动画使其逐渐消失...因为我喜欢动画...

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage img = ImageIO.read(getClass().getResource("/Chrome.png"));
                    ImageIcon icon = new ImageIcon(img);
                    JLabel label = new JLabel(icon);

                    JFrame frame = new JFrame("Testing");
                    frame.setUndecorated(true);
                    frame.setBackground(new Color(0, 0, 0, 0));
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                    Timer timer = new Timer(40, new ActionListener() {
                        float opacity = 1.0f;
                        float delta = 0.05f;

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            opacity -= delta;
                            if (opacity < 0.0f) {
                                opacity = 0.0f;
                                ((Timer)(e.getSource())).stop();
                                frame.dispose();
                            }
                            frame.setOpacity(opacity);
                        }
                    });
                    timer.setInitialDelay(2000);
                    timer.start();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}

好的,这里有很多内容,您需要通读 Concurrency in Swing and How to use Swing Timers 了解更多详细信息,不用说,入门有点复杂。

基本上,所有这一切所做的就是,等待 2 秒,然后每 40 毫秒,将帧不透明度降低一个因子或 0.05 直到它达到 0 然后它处理 window.

现在,我可能会混合使用这些技术,例如,我可能会显示徽标框架(可能设置为显示在顶部),然后显示主框架,然后触发徽标框架淡出.这可以通过控制器完成 class 以简化代码,但这取决于您。

A 还建议查看 Creating a GUI With JFC/Swing