import com.sun.awt.AWTUtilities;
public class TranslucentFrame extends JFrame {
public TranslucentFrame() {
AWTUtilities.setWindowOpacity(this, 0.6f); // 0.0~1.0
setTitle("半透明視窗");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) { new TranslucentFrame(); }
}
缺點: com.sun.* 非標準,JDK 9+ 模組化後默認不可訪問,需 --add-opens。
public class TranslucentFrame extends JFrame {
public TranslucentFrame() {
// 必須在 setVisible 前設置,且需底層視窗系統支援
setBackground(new Color(0, 0, 0, 0)); // 透明背景
setUndecorated(true); // 去除標題欄/邊框(可選)
// 整體不透明度
setOpacity(0.6f);
setTitle("標準半透明視窗");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
// 形狀:圓角矩形
setShape(new RoundRectangle2D.Double(0, 0, 400, 300, 30, 30));
// 漸變透明:需重寫 paintComponent
JPanel panel = new JPanel() {
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(new GradientPaint(0, 0, new Color(0,0,0,0.8f),
0, 300, new Color(0,0,0,0f)));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
panel.setOpaque(false);
setContentPane(panel);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
boolean translucent = gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
boolean perPixel = gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT);
System.out.println("整體透明: " + translucent + ", 像素級: " + perPixel);
| 問題 | 解決 |
|---|---|
| Linux 無合成器 | 需啟用 Compton/Picom 或 KWin/ Mutter |
| Windows 遠程桌面 | 透明度可能失效,檢測 perPixel 為 false 時降級 |
| setUndecorated(true) | 必須在 setVisible(true) 前調用 |
| 重繪閃爍 | 開啟雙緩衝 RepaintManager.setDoubleBufferingEnabled(true) |