Java 7 Swing支持具有透明和非矩形形状的窗口。 以下屏幕截图显示了创建的不透明度为75%的圆形窗口。
您可以通过在JFrame
上使用setOpacity
方法更改其不透明度来创建半透明窗口。 请注意,只有底层操作系统支持时,您才能创建半透明窗口。 另外,通过调用setUndecorated(true)
确保窗口未装饰。
改变窗口的形状,调用setShape
内部方法componentResized
方法,因此,如果窗口大小,形状被重新计算为好。
创建半透明圆形窗口的示例代码如下所示:
import java.awt.Color;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Ellipse2D;import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;public class TranslucentCircularFrame extends JFrame {/*** Creates a frame containing a text area and a button. The frame has a* circular shape and a 75% opacity.*/public TranslucentCircularFrame() {super("Translucent Circular Frame");setLayout(new GridBagLayout());final JTextArea textArea = new JTextArea(3, 50);textArea.setBackground(Color.GREEN);add(textArea);setUndecorated(true);// set the window's shape in the componentResized method, so// that if the window is resized, the shape will be recalculatedaddComponentListener(new ComponentAdapter() {@Overridepublic void componentResized(ComponentEvent e) {setShape(new Ellipse2D.Double(0, 0, getWidth(), getHeight()));}});// make the window translucentsetOpacity(0.75f);setLocationRelativeTo(null);setSize(250, 250);setDefaultCloseOperation(EXIT_ON_CLOSE);setVisible(true);}public static void main(String[] args) {// Create the GUI on the event-dispatching threadSwingUtilities.invokeLater(new Runnable() {@Overridepublic void run() {GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();// check if the OS supports translucencyif (ge.getDefaultScreenDevice().isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT)) {new TranslucentCircularFrame();}}});}
}
参考: Java 7 Swing:由我们的JCG合作伙伴 Fahd Shariff在fahd.blog博客上创建半透明和成形的Windows 。
翻译自: https://www.javacodegeeks.com/2013/07/java-7-swing-creating-translucent-and-shaped-windows.html