如何使 JFrame 的形状与具有透明背景的图像相同?

How to make JFrame same shape as Image with transparent Background?

我是 Java 的初学者,使用 NetBeans 作为我的 IDE...

我正在尝试制作一个自定义形状 JFrame,其形状与我将要创建的图像相似...我找到了解决方案 here and here 但我不知道如何应用它在 Netbeans 中..

花了我几个小时的时间研究但无济于事..所以我在这里问它希望有人能启发我......我也希望你解释使用的代码及其工作原理所以我也会学习并且只是复制粘贴...

I also hope you explain the codes used and how it worked

这就是教程的好处。阅读有关 How to Create Translucent and Shaped Windows 的 Swing 教程部分以获取信息和工作示例。

I can't figure out how to apply it in Netbeans

不要使用 IDE 生成代码。如果你换 IDE,那么你需要学习一个新的。而是花时间学习 Java/Swing,而不是 IDE。

在阅读和观看我找到的几个教程后,几个小时开始使用 NetBeans,我终于找到了一个简单的解决方案...

代码如下:

package testPack;

import java.awt.Color;
import javax.swing.*;
import java.awt.Dimension;

/**
 *
 * @author Karyuu Ouji
 */
public class TestPanel extends javax.swing.JPanel {

    /**
     * Creates new form TestPanel
     */
    public TestPanel() {

        initComponents();
        this.setPreferredSize(new Dimension(704,182));
        this.setOpaque(false);
        this.setDoubleBuffered(true);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setLayout(null);

        jButton1.setText("Close");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton1MouseReleased(evt);
            }
        });
        add(jButton1);
        jButton1.setBounds(593, 0, 110, 23);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/testPack/sao.png"))); // NOI18N
        jLabel1.setText("jLabel1");
        add(jLabel1);
        jLabel1.setBounds(0, 0, 704, 180);
    }// </editor-fold>                        

    private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {                                       
        System.exit(0);
    }                                      

    public static void main(String[] args) {

        JFrame frmMain = new JFrame();
        frmMain.setUndecorated(true);
        frmMain.setBackground(new Color(0,0,0,0));
        frmMain.add(new TestPanel());
        frmMain.pack();
        frmMain.setLocationRelativeTo(null);
        frmMain.setVisible(true);

    }


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

注意:大部分代码由 NetBeans 生成

我所做的只是从组件托盘中添加一个 JLabel,并将 JPanelJLabel 的大小设置为与图像大小相同。

然后我通过 Icon 属性.

把图像放到 JLabel

Setting Icon/Image

这是我 运行 应用程序时的样子。

Running

我希望这对以后像我这样的人有所帮助...:)