2013-02-18 2 views
13

私はJFrameを透明にしたいが、その上にある画像は不透明にしたい。これは私が今持っているものです。透明なJFrameを作成するにはどうすればよいですか?

enter image description here

誰もが唯一JFrameを透明にする方法を知っていますか?

import javax.swing.*; 
import java.awt.*; 
import com.sun.awt.AWTUtilities; 
import static java.awt.GraphicsDevice.WindowTranslucency.*; 

public class SplashDemo extends JFrame 
{ 
    public SplashDemo() 
    { 
     setUndecorated(true); 
     setSize(200, 200); 

     add(new JLabel(new ImageIcon("puppy2.png"))); 
     setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     setVisible(true); 

     setOpacity(0.85f);  
    } 

    public static void main(String[] args) 
    { 
     new SplashDemo(); 
    } 
} 
+1

を意味します。内容ペイントを半透明にし、内容を不透明にします。 – MadProgrammer

答えて

26

は基本的に、あなたは透明な窓と半透明のコンテンツペインを行う必要があります。

は、ここに私のコードです。これは、フレームを透明に...コンテンツ・ペインに追加何が追加alpheringなしでレンダリングされていきます

enter image description here

public class TranscluentWindow { 

    public static void main(String[] args) { 
     new TranscluentWindow(); 
    } 

    public TranscluentWindow() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        try { 
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
        } catch (Exception ex) { 
        } 

        JWindow frame = new JWindow(); 
        frame.setAlwaysOnTop(true); 
        frame.addMouseListener(new MouseAdapter() { 
         @Override 
         public void mouseClicked(MouseEvent e) { 
          if (e.getClickCount() == 2) { 
           SwingUtilities.getWindowAncestor(e.getComponent()).dispose(); 
          } 
         } 
        }); 
        frame.setBackground(new Color(0,0,0,0)); 
        frame.setContentPane(new TranslucentPane()); 
        frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png"))))); 
        frame.pack(); 
        frame.setLocationRelativeTo(null); 
        frame.setVisible(true); 
       } catch (IOException ex) { 
        ex.printStackTrace(); 
       } 

      } 
     }); 
    } 

    public class TranslucentPane extends JPanel { 

     public TranslucentPane() { 
      setOpaque(false); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 

      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f)); 
      g2d.setColor(getBackground()); 
      g2d.fillRect(0, 0, getWidth(), getHeight()); 

     } 

    } 

} 
+1

うわあ、ありがとうございました。それはたくさんの仕事でしたか?あなたが研究をするのに多くの時間を費やしたようです。 – r1nzler

+3

いいえ - この種のものはいつもします;) – MadProgrammer

+2

+1、クールです。 JDK7ではあまりプレイしていません。私はトップレベルのウィンドウを透明にするのがとても簡単だとは気付かなかった。あなたがする必要があるのは、透明な背景色を使用することだけです。 – camickr