简体   繁体   中英

AWTUtilities Transparent JFrame

Using this article from sun. I am trying to create a transparent window.

I have one image inside a label on the frame. I want the image to be visible but the frame invisible.

When i use


try {
   Class awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
   Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
   mSetWindowOpacity.invoke(null, window, Float.valueOf(0.75f));
} catch (NoSuchMethodException ex) {
   ex.printStackTrace();
} catch (SecurityException ex) {
   ex.printStackTrace();
} catch (ClassNotFoundException ex) {
   ex.printStackTrace();
} catch (IllegalAccessException ex) {
   ex.printStackTrace();
} catch (IllegalArgumentException ex) {
   ex.printStackTrace();
} catch (InvocationTargetException ex) {
   ex.printStackTrace();
}

It makes everthing transparent is possible to keep components not transparent.

You could try just setting the alpha channel for the background color of your frame, that shouldn't descend to components.

window.setBackground(new Color(1.0, 1.0, 1.0, 0.25));

should give you a white, transparent window.

You can still use the AWTUtilities class, but instead of setting the opacity with setWindowOpacity() setWindowOpaque(). This will turn off the background of the window, but anything you draw inside the window will still be drawn as before. As of the recent Java 6 updates this is now the correct way to do things. AWTUtilities will work on both Mac & MS Windows. These methods will be moved into java.awt.Window itself in Java 7.

You need to set the opacity of the child components, something like

childComponent.setOpaque(true);

That will make them opaque, without making the frame opaque.

I'd like to expand on a previous answer with the following. This will create a window with 0.05 transparency or 12.75 out of 255. Then the components are set to a transparency of 0.50f this will only effect clickable components. Non clickable like Labels can have their transparency set to what ever. This however patches the clickable components problem of it changing colors.

JWindow subFrame = new JWindow();           
subFrame.setBounds(0, 0, 500, 500);
subFrame.setAlwaysOnTop(true);
subFrame.setOpacity(0.50f);
subFrame.setBackground(new Color(1.0f, 1.0f, 1.0f, 0.05f));

JButton button = new JButton("Hello");
button.setBounds(20, 180, 100, 40);

subFrame.getContentPane().setLayout(null);
subFrame.getContentPane().add(button);
subFrame.setVisible(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM