Monday, February 18, 2008

Play Safe with Swing

Last month, I was writing a GUI based code in Java. As Swing provides rich UI so I decided to go for Swing. Here is a simple piece of Suggestion, which most of us know already. If you are a novice in Swing, you always need to take care in calling UI work. Reason is simple, swing is not thread-safe and calling GUI work randomly will lead to a deadlock in code. We are seeing 'n' no. of problem with Swing code, just because developers don't know(or maybe forget) that swing is not a thread-safe world. Sometime you are not able to see the problem initially but afterward when your code is going heavier and heavier you will face lot of problems.

How to make Swing Thread-safe ?

Its not a tough job. First see this, this is more or less like a rule and you can apply anywhere to write a safe code:

public static void main(String[] args) {
JFrame frame = new JFrame();;
// Anything after this is going to be crappy and thread unsafe

If you are going to write two UI work, and since things are not synchronized, you can go into a big mess. I wanted to post my code where I got the problem some days back, but its too big to post. No worries I got a code from here which is amazing ! You know what is cool, it crashes every time :)

import javax.swing.*;
import java.awt.*;

public class StrangeProblem extends JFrame {
static {
new StrangeProblem();

private static void staticMethod() {
System.out.println("This is never reached");

private StrangeProblem() {
getContentPane().add(new MyJDesktopPane());
setSize(300, 300);
// If commented out, program works fine, otherwise it hangs
new JInternalFrame();

private class MyJDesktopPane extends JDesktopPane {
protected void paintComponent(Graphics g) {
System.out.println("We will now call the static method...");
System.out.println("Static method was called.");

public static void main(String[] args) {

(Thanks for the poster of this code)

So now you got the thumb rule, what not to do ! Alright time to see what to do.

Simple. Run your code in the event-dispatching thread. Most of the UI like event, mouse clicks are always handled by event-dispatching thread. SwingUtilities class provide two methods invokeLater() and invokeAndWait() to get rid of this problem. Now, why two different methods is a big mystery, but use invokeLater() if its a case of Swing. So, now the code skeleton is :

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();;
// you can write more UI work here

I can leave it on to you to make the above code deadlock free :). For more detail, see the SwingUtilities class JavaDoc.

1 comment:

Anonymous said...

Do You interesting how to [b]Buy Viagra in Canada[/b]? You can find below...
[size=10]>>>[url=][b]Buy Viagra in Canada[/b][/url]<<<[/size]

[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also you can find on our sites.
Generic Viagra is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.