Full Version: Make a transparent swing UI components
Dream.In.Code > Programming Tutorials > Java Tutorials
lordms12
In this tutorial I will explain how to create transparent swing UI components.

Let’s start with simple example of how to make a transparent button:
java
class TransparentButton extends JButton {
public TransparentButton(String text) {
super(text);
setOpaque(false);
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
super.paint(g2);
g2.dispose();
}
}


To use TransparentButton instead of JButton all what you want to modify is transparency level (I will show you how in next paragraph) and overwrite constructors you want as the above code.

All what you want to change transparency level is to change the 0.5f value in line g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
To make it clearer
0.0f means 100% transparent (you will not see it)
0.5f means 50% transparent
1.0f means 0% transparent (Not transparent at all)


Let’s try this way now with popup menu:
java
class TransparentPopupMenu extends JPopupMenu {
public TransparentPopupMenu() {
super();
setOpaque(false);
}
}

class TransparentMenuItem extends JMenuItem{
public TransparentMenuItem(String text) {
super(text);
setOpaque(false);
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
super.paint(g2);
g2.dispose();
}
}


Note: You can get rid of TransparentPopupMenu class but in this case you have to remember to call setOpaque(false); after initialize JPopupMenu object

And you can try this way with other components.
abgorn
A picture that shows the effects of this code would be nice. If you wouldn't mind, it would be helpful.
lordms12
QUOTE(abgorn @ 6 Aug, 2008 - 03:30 PM) *

A picture that shows the effects of this code would be nice. If you wouldn't mind, it would be helpful.

Click to view attachment
Click to view attachment
abgorn
Thanks, I hope to use it in my own work. biggrin.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.