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

30 comments:

Hazem 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.

rofl 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

aiyipianni said...

Aston Villa rode their luck at Hull City where an 88-minute own goal from Kamil Zayatte saw them leapfrog three points clear of Arsenal and into fourth place in the Premier League wow gold with a 1-0 win.

Villa had to survive Hull penalty appeals for a handball against Ashley Young in time added on, television replays showing that referee Steve Bennett wow gold correctly rejected the claims after consulting a linesman.

Bennett had been involved in controversy after just five minutes when American goalkeeper Brad Friedel looked to have handed Hull the initiative and threaten Villa's return to the Champions League qualifying wow gold zone.

Friedel spilled wow gold the ball under pressure from Nick Barmby and stand-in right-back Nigel Reo-Coker turned it into his own net as he attempted to wow gold clear.

But Bennett cut short wow gold celebrations at the KC Stadium -- and let Friedel off the hook -- when he ruled out the score for an apparent infringement by Barmby.

Zayatte's intervention from a Young cross bound for wow gold Gabriel Agbonlahor then saw Villa leapfrog Arsenal and draw level with Manchester United on 38 points -- seven adrift of leaders Liverpool and four wow gold behind Chelsea.

Stung by an on-pitch dressing down wow gold by manager Phil Brown at Manchester City last week, Hull showed five changes and a vastly improved performance.

Promoted Hull were looking for only their second win in 11 games while wow gold Villa arrived unbeaten in seven and it looked to be heading for a goalless draw when the home side suffered a cruel late blow.

aiyipianni said...

British tennis ace Andy wow po Murray can expect a massive income wow or injection after joining the same wow po management group that handles the likes wow or of David Beckham and Cristiano Ronaldo.

Simon Fuller's 19 Entertainment, wow geld partnered with CAA Sports, signed world number four LOTR Gold Murray and doubles-playing brother Jamie for representation across all LOTR Gold their on and off court activity from LOTR gold March 2009.

"Jamie and I buy Warhammer gold/a> feel we've made big progress in the last couple of years on court," Warhammer gold 21-year-old 2008 U.S. Open runner-up Andy said on his Web site.

"It's important that Warhammer gold we have the very best team around us to take care of business while buy Warhammer gold we concentrate 100% on our tennis. Warhammer gold So this is a fantastic opportunity for us to work with buy Warhammer gold Simon Fuller, 19 and CAA Sports.

"We now have an Warhammer gold unbeatable combination of representatives buy Warhammer gold with world-class stature and experience, and Warhammer gold we are really excited by what we can achieve buy Warhammer gold together".

Fuller's company, which Warhammer gold is run from London, New York and LA, wow gold has partnered with CAA Sports, and already represents world of warcraft gold the world No. 3 Novak Djokovic.

American Idol creator Fuller buy wow gold commented: "I am very cheap wow gold excited to be working with Andy and Jamie, wow power leveling two of the brightest British wow powerleveling talents in global sports.

"Their determination dofus kamas to succeed has become a kamas dofus trademark in their game and their progress as professional Lord of the Rings Online Gold sportsmen has taken them to the LOTRO Gold top in world tennis.

"19's innovative LOTR Gold partnership with CAA Sports will provide them fly for fun penya with an unparalleled level of flyff penya global support".

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

Anonymous said...

Do you know the warhammer gold, In here you can buy the warhammer Online gold, Do you know that the warhammer money in the game is very important, If you had more cheap warhammer Online gold . I think you can get the tall level, quickly come here to buy warhammer gold.

Welcome to the 2moons dil, In here you can buy the 2moons gold, Do you know that the 2moon dil in the game is very important, If you had more cheap 2moons gold. I think you can get the tall level, quickly come here to buy 2moons dil.

WoW Gold Guide said...

good post

Aion chinese gold said...

I like play online game, I also buy Aion gold and Aion onilne gold, the Aion china gold is very cheap, and use the Aion China kina can buy many things, I like Aion chinese gold, thanks, it is very good.

j 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

nike said...

http://www.polosales.com/ : cheap polo shirts
http://www.polosales.com/ : polo shirt
http://www.polosales.com/ : lacoste polo shirts
http://www.polosales.com/ : ralph lauren polo shirts
http://www.polosales.com/ : wholesale polo shirts
http://www.superpolos.com/mens-lacoste-solid-classicfit-polo-shirt-light-yellow-p-146/ : Yellow Polo Shirt
http://www.superpolos.com/wholesale-mens-short-sleeve-lacoste-polo-shirts-p-132/ : Men's Polo Shirts
http://www.superpolos.com/wholesale-mens-short-sleeve-lacoste-polo-shirts-p-133/ : Wholesale Polo Shirts
http://www.superpolos.com/ : polo shirts
http://www.superpolos.com/ : Lacoste polo shirts
http://www.pumachaussure.com/ : chaussure puma
http://www.pumachaussure.com/ : chaussures puma
http://www.polocart.com/ : polo shirts

bing said...

http://www.chihairstraightener.us/ : chi hair straightener
http://www.chiflatiron.us/ : chi flat iron

http://www.polool.com/ : new polo shirts


http://www.pursecart.com/ : cheap handbags
http://www.pursecart.com/ : cheap bags
http://www.pumachaussures.com/ : puma chaussures
http://www.pumachaussures.com/ : chaussures puma
http://www.pumachaussure.com/ : chaussure puma

http://www.jacketsworld.com/ : Men's North Face
http://www.jacketscart.com/ : Women's North Face


http://www.myhairstraighteners.co.uk/ : hair straighteners
http://www.sexylingeriestore.us/ : sexy lingerie store
http://www.uggsoutlet.us/ : cheap ugg boots
http://www.12hot.com/ : tattoo wholesale
http://www.polooo.net/ : men's clothing
http://www.acrazystore.com/ : women's clothing




http://www.thehairstraighteners.com/ : cheap hair straighteners
http://www.polosales.com/ : cheap Lacoste polo shirts
http://www.superpolos.com/ : cheap Lacoste polo shirts
http://www.shoesbuying.com/ : 2009 nike shoes
http://www.shoesbuying.com/2009-nike-shoes-c-153.htm : new nike shoes
http://www.shoesbuying.com/air-max-classic-bw-c-185.htm : Women's max
http://www.shoesbuying.com/mens-max-93-c-188.htm : Men's max 93
http://www.shoesbuying.com/nike-shox-c-165.htm : nike shox
http://www.shoesbuying.com/nike-force-c-174.htm : Nike air force
http://www.shoesbuying.com/nike-2003-c-181.htm : Nike air max 2003
http://www.shoesbuying.com/nike-air-max-ltd-c-166.htm : nike air max ltd
http://www.shoesbuying.com/nike-air-max-tn-c-167.htm : nike air max tn
http://www.shoesbuying.com/nike-rift-shoes-c-162.htm : Nike air rift
http://www.shoesbuying.com/nike-yeezy-c-184.htm : Nike air Yeezy
http://www.shoesbuying.com/nike-airmax-c-154.htm : nike airmax
http://www.shoesbuying.com/nike-airmax-c-155.htm : Nike air max 90
http://www.shoesbuying.com/nike-airmax-c-157.htm : Nike air max 97
http://www.shoesbuying.com/nike-birds-nest-shoes-c-152.htm : nike birds nest shoes
http://www.shoesbuying.com/nike-dunk-high-c-177.htm : nike dunk
http://www.shoesbuying.com/nike-shoes-c-168.htm : nike RT1 shoes
http://www.shoesbuying.com/nike-sb-c-180.htm : nike SB
http://www.shoesbuying.com/nike-shox-shoes-c-156.htm : nike shox shoes
http://www.shoesbuying.com/nike-shox-shoes-c-158.htm : Nike shox OZ shoes
http://www.shoesbuying.com/nike-shox-shoes-c-159.htm : Nike shox R2 shoes
http://www.shoesbuying.com/nike-shox-shoes-c-160.htm : Nike shox R3 shoes
http://www.shoesbuying.com/nike-shox-shoes-c-163.htm : Nike shox R4 shoes
http://www.shoesbuying.com/nike-shox-shoes-c-164.htm : Nike shox R5 shoes
http://www.shoesbuying.com/nike-shox-c-171.htm : Nike shox TL3
http://www.shoesbuying.com/nike-trainers-lovers-c-118.htm : nike trainers lovers

http://www.racketsoffer.com/ : tennis rackets
http://www.racketsoffer.com/wilson-racquets-c-19/ : Wilson tennis rackets
http://www.racketsoffer.com/head-racquets-c-18/ : HEAD tennis rackets
http://www.racketsoffer.com/babolat-racquets-c-17/ : Babolat tennis rackets

yiran said...

Your blog is very good, it's the best blog I've ever seen, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do? I'd like to introduce myself as the outlet of polo t shirts women, polo t shirts on sale, and polo t shirts for women. These products are our masterpieces, such as polo shirts on sale, polo shirts men, men's polo shirt, men polo shirt, mens polo shirts, mens polo shirt, besides we also sell cheap polo shirts, discount polo shirts, men's polo shirts, women's polo shirts. We are also the outlet of, cheap tennis racket, discount tennis racket, we recommend prince tennis racquet, head tennis rackets, wilson tennis racket, babolat tennis racquet. And it is our great pleasure that you come to our store online!

Roxy said...

Costa rica tours, shopping online, costa rica fishing, jaco fishing charters, costa rica whale watching, costa rica dolphin watching, costa rica party boat, panama fishing, fishing costa rica los suenos, los suenos fishing charters, costa rica fishing los suenos, los suenos costa rica fishing, costa rica los suenos fishing, fishing costa rica los suenos, los suenos fishing charters, costa rica fishing los suenos, los suenos costa rica fishing charters, costa rica los suenos fishing, Los suenos fishing, Fishing costa rica los suenos, Costa Rica Rafting,
http://www.kingtours.com/.

dfadf said...

The Tax Return Crack-Up<2>
I was not shocked because this was old news -- practically ancient, in fact. In R. Microsoft Office Emmett Tyrrell, Office 2010 Jr.'s most recent book The Clinton Microsoft Office 2010 Crack-
Up, page fiv Office 2007 e, paragraph two, we learn that in Bill Clinton's "first four years out of the White H Microsoft Office 2007 ouse, he ea Office 2010 key rned over Office 2010 download $43 million Office 2010 Professional after
expenses... Microsoft outlook "
The next Outlook 2010 page directs Windows 7 us to Appendix Microsoft outlook 2010 I, a list of the conniving couple's fees for speeches and book royalties and other income. The first

Anonymous said...

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

andre12323 said...

christian louboutin shoeschristian louboutin shoes
christian louboutin bootschristian louboutin boots
christian louboutin sandalschristian louboutin sandals
christian louboutin slingbackchristian louboutin slingback
christian louboutin sneakerschristian louboutin sneakers
christian louboutin wedgeschristian louboutin wedges
christian louboutin weddingchristian louboutin wedding
timberland bootstimberland boots
asics shoesasics shoes
asics running shoesasics running shoes
dsquared jeans mendsquared jeans men
dsquared shoes 2011dsquared shoes 2011
karen millen dresseskaren millen dresses
marque t shirtmarque t shirt

abercrombiefitch said...

the iconic sneaker was originally introduced on now.
Nike Air Max 2011
Nike Air Max Shoes
Nike Air Max
Nike Air Max Wildwood Supreme
Nike Air Max Turbulence
Nike Air Max Skyline
Nike Air Max Goadome
Nike Air Max Fitsole
Nike Air Max Zenyth
Nike Air Max Boots
Nike Air Max Zoom Kobe
Nike Air Max Tn
Nike Air Max LTD
Nike Air Max Presto
Nike Air Max BW
Nike Air Max 24 7
Nike Air Max 2010
Nike Air Max 2011
Nike Air Max 2009
Nike Air Max 95
Nike Air Max 91
Nike Air Max 87
Nike Air Max 180
Nike Air Max Griffey Max 1
Nike Air Max 90
Nike Air Max 1
Abercrombie and Fitch London
Abercrombie & Fitch Clothes
Vibram Shoes
Cheap Air Max
Nike Air Max Shoes
is available in a vivid array of colors, including, Jiffy Black, Pigeon Grey, Shell White, Dodger Blue, and Beaver Brown.

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

sport said...

Discount Uggs
Discount Ugg Boots
Ugg Boots Discount
Uggs Discount
Discount Uggs Boots