如何在 java 中创建透明的 JFrame 背景但保持按钮可见?
How to create background of JFrame transparent in java but keeping buttons visible?
我通过以下方式使我的 JFrame 透明:
myFrame.setUndecorated(true);
myFrame.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
它使 JFrame 透明,但也丢失了 window 删除和关闭按钮。
为了使 window 可见,我使用了
AWTUtilities.setOpacity(this, 0.5f);
但是我发现这个方法只适用于java6,并且打包在AWT包中,在java7中被限制,并且在java7中也改变了方法现在
Window.setOpacity(float opacity);
但它不起作用,谁能告诉我如何使透明 window 和按钮与透明框架一起可见。
这会使框架看起来有点不同,但我认为这就是您想要的:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
JPanel panel = new JPanel();
panel.add(new JButton("Button"));
setContentPane(panel);
setBackground(new Color(0, 0, 0, 0));
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
}
如果有效,它应该如下所示:
我通过以下方式使我的 JFrame 透明:
myFrame.setUndecorated(true);
myFrame.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
它使 JFrame 透明,但也丢失了 window 删除和关闭按钮。 为了使 window 可见,我使用了
AWTUtilities.setOpacity(this, 0.5f);
但是我发现这个方法只适用于java6,并且打包在AWT包中,在java7中被限制,并且在java7中也改变了方法现在
Window.setOpacity(float opacity);
但它不起作用,谁能告诉我如何使透明 window 和按钮与透明框架一起可见。
这会使框架看起来有点不同,但我认为这就是您想要的:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
JPanel panel = new JPanel();
panel.add(new JButton("Button"));
setContentPane(panel);
setBackground(new Color(0, 0, 0, 0));
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
}
如果有效,它应该如下所示: