在 java swing 中创建一个透明的 JFrame [英] Create a transparent JFrame in java swing

查看:19
本文介绍了在 java swing 中创建一个透明的 JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在java中做了一个swing应用,但问题是我如何在java中实现透明框架.

Hello everyone im made a swing application in java, but problem is that how i can achive the transparent frame in java.

我想制作一个用户界面设计,如附加图像,但问题是框架不透明,因此如果该层上没有组件,它会显示默认颜色.

I want to make a user interface design as in attach image, but probem is that frames is not transparent, so it showing the default color if there is no components on that layer.

就像在右侧一样,我想在顶部自由和底部自由部分将此框架显示为透明,

Like on the right side i want to show this frame as a transparent on the top free and bottom free portion,

我使用 AWTUtilities,但它不适合我.

I use AWTUtilities, but it not works for me.

我该怎么做,请回复,

还给我一个提示,在未装饰的窗口中通过标题栏拖动窗口

also give me a hint to drag the window by title bar, in undecorated window

提前致谢

推荐答案

透明背景组件

public class TransparentBackground extends Jcomponent { 
    private JFrame frame; 
    private Image background;

public TransparentBackground(JFrame frame) {
    this.frame = frame;
    updateBackground( );
}

public void updateBackground( ) {
    try {
        Robot rbt = new Robot( );
        Toolkit tk = Toolkit.getDefaultToolkit( );
        Dimension dim = tk.getScreenSize( );
        background = rbt.createScreenCapture(
        new Rectangle(0,0,(int)dim.getWidth( ),
                          (int)dim.getHeight( )));
    } catch (Exception ex) {
        p(ex.toString( ));
        ex.printStackTrace( );
    }
}
public void paintComponent(Graphics g) {
    Point pos = this.getLocationOnScreen( );
    Point offset = new Point(-pos.x,-pos.y);
    g.drawImage(background,offset.x,offset.y,null);
}
}

您可以使用一个简单的 main( ) 方法运行它,将一些组件放到面板上并将其放入框架中:

You can run this with a simple main( ) method, dropping a few components onto the panel and putting it into a frame:

public static void main(String[] args) {
    JFrame frame = new JFrame("Transparent Window");
    TransparentBackground bg = new TransparentBackground(frame);
    bg.setLayout(new BorderLayout( ));
    JButton button = new JButton("This is a button");
    bg.add("North",button);
    JLabel label = new JLabel("This is a label");
    bg.add("South",label);
    frame.getContentPane( ).add("Center",bg);
    frame.pack( );
    frame.setSize(150,100);
    frame.show( );
}

这篇关于在 java swing 中创建一个透明的 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆