• category: swing folder: WindowOpacity title: JFrameを半透明化 tags: [JFrame, Translucent, Transparent, JRootPane, ContentPane, TexturePaint] author: aterai pubdate: 2010-06-14T14:13:21+09:00 description: JFrameのタイトルや子コンポーネントを除く背景が半透明になるよう設定します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTWw2d9LNI/AAAAAAAAApw/NXG2EcaSv_s/s800/WindowOpacity.png hreflang:
       href: http://java-swing-tips.blogspot.com/2010/06/translucent-jframe.html
       lang: en

概要

JFrameタイトルや子コンポーネントを除く背景が半透明になるよう設定します。

サンプルコード

JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
//com.sun.awt.AWTUtilities.setWindowOpacity(frame, .5f);
com.sun.awt.AWTUtilities.setWindowOpaque(frame, false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.add(new JButton("JButton"));
p.setBackground(new Color(.5f, .8f, .5f, .5f));
frame.getContentPane().add(p);
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
View in GitHub: Java, Kotlin

解説

com.sun.awt.AWTUtilities.setWindowOpacity(frame, .5f);を使って半透明化すると、フレームのタイトルバーや、子コンポーネントまで半透明化されるので、代わりに上記のサンプルでは以下のようにして半透明化を行っています。

  • JFrame.setDefaultLookAndFeelDecorated(true);で、タイトルバーなどをJRootPaneに描画
  • com.sun.awt.AWTUtilities.setWindowOpaque(frame, false);JFrameを完全に透明化
    • JDK 1.7.0の場合は、代わりに、frame.setBackground(new Color(0x0, true));
  • ContentPanesetBackground(new Color(.5f, .8f, .5f, .5f));で半透明の背景色を設定したパネルを追加

参考リンク

コメント