Search code examples
javaswingtransparencyjnajava-5

How to add non-Transparent components to Transparent JFrame in java 1.5?


I have a subclass of JFrame(it contains JButton, Title and Jpanel) and i added a JPanel to it. Jpanel occupies center portion of borderlayout. I want to make JPanel to be transparent(it should see through the Frame window).

As i am doing it for Java 1.5, I used JFrame.setOpacity(0.0f) to set transparency of Jframe. By doing this all Components of JFrame(ie. button, Title ahd jPanel) are using same alpha level. But I want only JPanel to be Transparent.

I experimented with JLayeredPane by changing Z-order with the same result.

I am open to use external libraries like JNA(JNA windowsUtil is also doing the same as setOpacity() method) and using classes of java7 or java6 as external libraries to my application .

I even gone through some previously asked questions with no help:

Opaque components on transparent Java windows

Java: Transparent Windows with non-transparent components?

Re-paint on translucent frame/panel/component.


Solution

  • Use JNA's WindowUtils.setWindowTransparent() method to start with a completely transparent window. Any pixels painted into that window will have their alpha component preserved.

    JFrame f = ...
    WindowUtils.setWindowTransparent(f, true);
    // ensure JPanel content pane doesn't paint its (solid) background
    f.getContentPane().setOpaque(false);
    // Any other added components will be painted normally
    f.getContentPane().add(new JButton("I'm opaque"));
    

    This should deliver the desired results.

    If you want your container to be semi-transparent, or other opacity combinations, you'll need to clarify your desired results.