Java Transparent Window

How to make a transparent JFrame but keep everything else the same?

Basically, you need to make a transparent window and a translucent content pane. This will mean anything added to the content pane will continue to be rendered without additional alphering...

Sample Image

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());

}

}

}

How to draw images on transparent window?

  • BufferStrategy is normally associated with heavy weight components, which don't have any concept of transparency.
  • Transparent and translucent (per alpha pixeling) is not "officially" supported under Java 6
  • Making a window translucent effects anything else painted to it...this very annoying, regardless if you are using Java 6 or 7

The secret is to make the Window transparent to begin with, then overlay a transparent component that has a special "translucent" paint effect.

Under Java 6 (update 10 I think), there became available a private API called AWTUtilities which provide the ability to make a window transparent or translucent, the following example is based on that API.

Bouncy Birdy

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TransparentWindowAnimation {

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

public TransparentWindowAnimation() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

if (supportsPerAlphaPixel()) {
try {
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
setOpaque(frame, false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception exp) {
exp.printStackTrace();
}
} else {
System.err.println("Per pixel alphering is not supported");
}
}
});
}

public static boolean supportsPerAlphaPixel() {
boolean support = false;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
return support;
}

public static void setOpaque(Window window, boolean opaque) throws Exception {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
throw new Exception("Window opacity not supported");
}
}

public class PaintPane extends JPanel {

private BufferedImage img;

private int xPos, yPos = 100;
private int xDelta = 0;
private int yDelta = 0;

public PaintPane() {
while (xDelta == 0) {
xDelta = (int)((Math.random() * 8)) - 4;
}
while (yDelta == 0) {
yDelta = (int)((Math.random() * 8)) - 4;
}
setOpaque(false);
try {
img = ImageIO.read(new File("AngryBird.png"));
} catch (IOException ex) {
ex.printStackTrace();
}

Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xPos += xDelta;
yPos += yDelta;
if (xPos - (img.getWidth() / 2) <= 0) {
xPos = img.getWidth() / 2;
xDelta *= -1;
}
if (xPos + (img.getWidth() / 2) >= getWidth()) {
xPos = getWidth() - (img.getWidth() / 2);
xDelta *= -1;
}
if (yPos - (img.getHeight() / 2) <= 0) {
yPos = img.getHeight() / 2;
yDelta *= -1;
}
if (yPos + (img.getHeight() / 2) >= getHeight()) {
yPos = getHeight() - (img.getHeight() / 2);
yDelta *= -1;
}
repaint();
}
});
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 128));
g2d.fillRect(0, 0, getWidth(), getHeight());
int x = xPos - (img.getWidth() / 2);
int y = yPos - (img.getHeight()/ 2);
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}

}

Using transparent window in both Java 6 and Java 7

See How to Create Translucent and Shaped Windows.. It mentions a "per pixel" translucency that you can leverage to make a window with java 7 that has the look and feel of the translucent window from java 6 which is no longer available. So basically you'd have to code to accommodate either, or you could go with a "uniform translucency" which works with both.

Gradient Translucent Window

Java: Transparent Windows with non-transparent components?

IIUC, Translucent Windows applies to the entire java.awt.Window and contents, but you might try the approach shown below and in this example.

JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(new Color(0f, 0f, 0f, 0.1f));
f.setUndecorated(true);
f.add(new JLabel("<html>Testing<br>1, 2, 3</html>"));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);

JAVA - Creating and showing a transparent window with a button

  1. The button shows for me. Its opacity makes it hard to see.

  2. The default layout manager for the content pane of the frame is a BorderLayout. When you don't specify a constraint it is added the the CENTER. Any component in the CENTER is resized to fill the space available in the frame.

  3. You can add any component to the frame. If you add the button directly, then it will be resized to fill the frame. You need to understand how layout managers work.

Don't use a Panel, that is an AWT component. Use a JPanel for Swing.

point me towards a resource

Read the Swing Tutorial for many Swing basics. There are sections on:

  1. A Visual Guide to Layout Managers
  2. How to Create Translucent and Shaped Windows

Along with other basic demo programs to get you started.

Is it possible to make a window with a transparent background?

See How to Create Translucent and Shaped Windows (Java 7+).

Translucent window with button

..(SWT) uses the native window scheme, rather than an ugly/custom one. ..

Use Swing with the native PLAF.


Update 1

Me.

..you want component (button etc.), not Window (or ancestor) transparency?

To which you replied.

not necessarily the component itself, but the 'area' in which the component resides in. if you look at the Nested Layout Example above, you see the win 7's transparent border, then you see the normal gray background. I'd like that gray background to also be transparent.

Window with 'per pixel' translucency

You can create a window with per-pixel translucency, where each pixel has its own alpha value. With this feature you can, for example, create a window that fades away to nothing by defining a gradient in the alpha values.

And as an aside, that 3rd screenshot is actually the 2nd image ripped directly from the page that is linked in the 1st sentence of my reply (the same page where I got the above quote). Did you follow the link, read the page (look at the screenshots), try the working examples?



Related Topics



Leave a reply



Submit