Sunday, March 25, 2007

Create A Transparent Window in Java

I recently read a post the read Another Thing Java Cannot Do In Java. And it read:
"you cannot create a popup window shaped like this:

Thought Bubble

Because Java does not support transparent windows"

Well here is a cool code to create "Transparent Window" in java.For more you can go in for this awesome book Swing Hacks by Joshua Marinnaci it is the best book with many more awesome tricks i have a copy and recommend to everyone(a must buy for those who are seriously interested in java)

import java.awt.*;
import java.util.Date;
import javax.swing.*;
import java.awt.event.*;
public class BGTest1 {

public static void main(String[] args) {
JFrame frame = new JFrame("Transparent Window");
TransparentBackground bg = new TransparentBackground(frame);
bg.setLayout(new BorderLayout());

JButton button = new JButton("This is a button");
bg.add("North",button);
JLabel label = new JLabel("This is a label");
bg.add("South",label);
frame.getContentPane().add("Center",bg);
frame.pack();
frame.setSize(300,300);
frame.show();
}

}
class TransparentBackground extends JComponent
implements ComponentListener, WindowFocusListener,
Runnable {
private JFrame frame;
protected Image background;
private long lastupdate = 0;
public boolean refreshRequested = true;

public TransparentBackground(JFrame frame) {
this.frame = frame;

updateBackground();
frame.addComponentListener(this);
frame.addWindowFocusListener(this);
new Thread(this).start();
}

public void updateBackground() {
try {
Robot rbt = new Robot();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
background = rbt.createScreenCapture(
new Rectangle(0,0,(int)dim.getWidth(),(int)dim.getHeight()));
} catch (Exception ex) {
p(ex.toString());
ex.printStackTrace();
}
}

public void paintComponent(Graphics g) {
Point pos = this.getLocationOnScreen();
Point offset = new Point(-pos.x,-pos.y);
g.drawImage(background,offset.x,offset.y,null);
}


public void componentShown(ComponentEvent evt) { repaint(); }
public void componentResized(ComponentEvent evt) { repaint(); }
public void componentMoved(ComponentEvent evt) { repaint(); }
public void componentHidden(ComponentEvent evt) { }

public void windowGainedFocus(WindowEvent evt) { refresh(); }
public void windowLostFocus(WindowEvent evt) { refresh(); }

public void refresh() {
if(this.isVisible() && frame.isVisible()) {
repaint();
refreshRequested = true;
lastupdate = new Date().getTime();
}
}

/*
private boolean recurse = false;
public void quickRefresh() {
p("quick refresh");
long now = new Date().getTime();
if(recurse ||
((now - lastupdate) < recurse =" true;" location =" frame.getLocation();" recurse =" false;" lastupdate =" now;" now =" new"> 1000)) {
if(frame.isVisible()) {
Point location = frame.getLocation();
frame.hide();
updateBackground();
frame.show();
frame.setLocation(location);
refresh();
}
lastupdate = now;
refreshRequested = false;
}
}
} catch (Exception ex) {
p(ex.toString());
ex.printStackTrace();
}
}


public static void p(String str) {
System.out.println(str);
}

}

here is the link to the book again

a must buy for those who are seriously interested in java

18 comments:

Hazem Saleh said...

Man Nice Post (Y)

technomage said...

If you really want to make that thought bubble, you can use this: http://rabbit-hole.blogspot.com/2007/02/non-rectangular-windows-update.html.

Trust me, it's a lot nicer than the robot hack.

Anonymous said...

lol.. nice idea but i dno if you tested it cos it doesnt even compile :P

Ashish Lijhara said...

rofl i tested it and it works wonders copy the code properly....
:)

Ashish Lijhara said...

well technomage i know that very well and i appreciate your help..and have even been using jna. but i want to find out a way to do it in pure java manner.I have been working on possible ways to do that but i have a limitation that i am a student and my exams are around the corner i'll be able to put my full effort to it as soon as i am done with my exams.i also would like to tell you that yahoo widget engine is also using that robot method please wait for my next post to see that

Anonymous said...

The code is either incomplete or broken. See line 76,
/*
private boolean recurse = false;

There is no */ to close the comments.

Anonymous said...

BGTest1.java:23: TransparentBackground is not abstract and does not override abs
tract method run() in java.lang.Runnable
class TransparentBackground extends JComponent
^
BGTest1.java:48: cannot find symbol
symbol : method p(java.lang.String)
location: class TransparentBackground
p(ex.toString());
^
Note: BGTest1.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
2 errors
Press any key to exit

Anonymous said...

Nice Programm! But it's not real transparency!!! Changes that happen behind the application Window are not recognized!
But I think Java 6 update 10 will help soon to solve this problem. Till then I'll use SWT!

Greetings

Anonymous said...

Its awesome yaar

Web Tasarımcı said...

thanks this post..



web tasarım
Wp Theme , Wp Plugin , Wp Tema , Free Premium Theme
msn indir, msn nickleri, msn resimleri, msn nickleri
ozalit , kırtasiye , dijital baskı, Fotokopi

WoW Gold Guide said...

good post

Anonymous said...

columbia jacketspyder jacketed hardy clothing ed hardy clothesed hardy shirts ed hardy t-shirts ed hardy sunglasses ed hardy mensed hardy womens head junior tennis racketwilson tennis racquet
wilson tennis racket
head tennis racketbabolat tennis racket

Anonymous said...

runs, but without any effect :>
event the runnable is wrong ...

web tasarım said...

web tasarımtüp bebekobeziterobotik cerrahipdkskamera sistemleriturnike sistemleriboğaz turulazer epilasyonlazer epilasyonkavitasyon ile zayıflama

dell servis said...

sharing is very beatiful thanks

rays said...

sharing is very good and high quality

Perde said...

Sharing a very informative and useful

Nike soccer cleats said...

Said was wonderful, really the best site! Liked by the way best described 2011 Nike soccer cleats