Showing posts with label SWING. Show all posts
Showing posts with label SWING. Show all posts

Sunday, July 13, 2008

Bio-Rhythmic Cycles - I got curious about bio-rhythmic cycles & wanted to try out the the results on my life.

For those who don't know what bio rhythmic cycles are, here is explanation:

The theory of biorhythms claims that one's life is affected by rhythmic biological cycles, and seeks to make predictions regarding these cycles and the personal ease of carrying out tasks related to the cycles. These inherent rhythms are said to control or initiate various biological processes and are classically composed of three cyclic rhythms that are said to govern human behavior and demonstrate innate periodicity in natural physiological change: the physical, the emotional, and the intellectual (or mental) cycles. Others claim there are additional rhythms, some of which may be combinations of the three primary cycles. Some proponents think that biorhythms may be potentially related to bioelectricity and its interactions in the body


I wrote a sample application in swing, which basically takes the date of birth as input & generate the charts.


Here is the sample screenshot, I used JFreecharts & some Date manipulating APIs to create above application. BTW is there any way I can show applet in this blog? Please let me know.

The results were interesting, Most of the events in my life had some kind of correlation with the above graph & explanation:

Physical cycle - 23 days; coordination strength well-being

Emotional cycle - 28 days; creativity sensitivity mood perception awareness

Intellectual cycle - 33 days; alertness analytical functioning logical analysis memory or recall communication

I also tried correlate our god Sachin's best innings with these cycles & surprisingly, cycle behaviour used to match with his best time :-)

Anyway I will try out with some other important figures before coming to conclusion these cycles have any impact or it's just a humbug. BTW, I am little skeptical about all astrology stuff.

So I am planning to develop a RESTful sample as well sample mobile application accepting date of birth & generating the charts possibly using Google charts instead of Jfreecharts

Friday, August 17, 2007

Some tips on developing Swing applications:

I recently developed one small application in swing . Here are some comments on tricks & libraries I used.

1. Using Template Method Pattern to simplify code

ActionTemplate :

JButton button = new JButton("Ok");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
//do some stuff here
}
});


This is how usually we handle the actions (I don't believe in separating out actionlisteners code from components declarations, it is always easier/better to keep them as near as possible) Anonymous classes provides easier way of achieving this;

from the above code I noted that,
1. In anonymous class, I will never use ActionEvent class & I don't want see it. It's an intrusive model.
2. Many times I want to handle actions asynchronously (like using SwingUtilitilities.invokeLater() routine), I don't want to repeat in every action listeners code.
3. I also want to display a wait cursor during this time & should be optional way of passing the icon @ runtime;
4. I also want to print the time taken & memory consumed for each actions; & I don;t want to repeat that, I also want to take that out from the code once the application in production.
6. actionPerformed method name is not intuitive, although ActionEvent not used 90% of time I do use it 10% of time when I write inner or separate ActionListener classes, it should be available for me.

Here is how I propose to handle this using template pattern.

ActionTemplate is abstract class having clicked() as abstract method & with default implementation for all other features.

button.addActionListener(new ActionTemplate() {
public void clicked(){
//do some stuff here
}
});
This is fine for me 90% of time.Now code is less & looks simpler. This is clearly non-intrusive model & all the extra features are defaulted and can be easily changed by over-riding when required. (Convention over configurations)

In case to handle the event asynchronously whenever some tasks lot of time, we can over-ride isAsynchronus call. isAsynchronus() will return false by default.

button.addActionListener(new ActionTemplate() {
public void clicked(){
//Some lengthy stuff here, So cannot make AWTDispatch thread to wait till it's completed
}
public boolean isAsynchronus(){
return true;
}
});


Similarly there can be callback methods for setting the wait cursor, monitoring completion status, (getWaitCursorIcon(), done() etc...)
We can also get the ActionEvent which is member variable for ActionTemplate class.

Similarly for WindowTemplate we can add closed, closing, max(), min() etc...
& for MouseTemplate methods like pressed(), clicked(), hover(), rightClikced(), doubleclicked() etc...
These will easier to understand & code than their Listener counterparts. I guess this approach is near to closures. Lack of closure in java is really a bottleneck while coding event handling. We are forced to deal with anonymous & final variables

Although I don't feel these tricks can be used in large projects (As adding more APIs to likely to confuse more) but this type of techniques will be very useful when we write applications in a very small team or by a single person, where using AOP, XML, Properties file based action handling framework using reflection is not an option (because of learning curve & the increase in total java source/jar size)

2. Window Dissolving tricks
While going through the
Swing Hacks book, I came across one dissolving hack. I also wrote some inspired from that, although they are too simple but can give window closing a different experience :-), Feel free to copy & use it from here.

3. External libraries
There is no point re-inventing the wheel, there are abundant high quality JFC components freely available, but the problem is most of them will come big baggage (in terms of size & API complexity).
I used these libraries & had no problem whatsoever with these.
JFreeCharts - For reporting through charts
iText - For Generating the pdf reports
I have used these excellent libraries in the past (but with J2ee applications)
DesignGridLayout - As layout manager

It is always better to code these in such a manner that if even when we take out these jars, application should work properly.It is always better to make these libraries not to be part of core functionalities. I handled these by neglecting ClassNotFoundException in appropriate place where-ever I am using such libraries. In case of applet & webstart it is not practical to use these heavy libraries as they increase the download time & there might be issues with licensing as well. So for an applet/java webstart versions JFree charts, iText & other external jars will not be included, I just remove these jars from library to make it light weight, that's it no code change required :-)

4. Layout Manager
I did not wanted to use the GridBagLayoutManager, it was regarded as un-necessarily complex for developing Swing applications. I tried out generating UI with my favorite IDE NetBeans. I did not like the code it generated. May be I need adjust with this kind of code in future. First the code generated was looking ugly & I wanted to use my custom components which I need to add & I like doing small tasks by defining actionlisteners there itself, the code generated lot of default methods. As of now I can think of using it only for prototype.



I looked into layout managers who all claimed to be better alternative to GridBagLayoutManager, I actually looked into the code of most of these layout managers & they are indeed provide lot ease in developing layouts,some introduce more complexity
I came across this debate on from layout manager showdown, All kudos to John for the splendid job done by comparing layout managers.
I found MigLayout to be best in solving all types of complex requirements, But for my screens I found DesignGridlayout the simplest after going through the sample code. As it is based in standard JDK library, this should be first choice for developing simple grid based screens.

For example, I wanted to design my layout something like this;

& it took 12 lines to do that, & code was too simple.


public void build(DesignGridLayout layout){
layout.row().center().add(title());layout.row().height(10);
layout.row().center().add(new JLabel("Email ")).add(user());
layout.row().height(5);
layout.row().center().add(new JLabel("Password ")).add(pwd());
layout.row().height(5);
layout.row().center().add(new JLabel("Exam List")).add(examList());
layout.row().height(5);
layout.row().center().add(signIn());
layout.row().height(15);
cancelButton = new JButton("Cancel");
loginButton = new JButton("Ok");
layout.row().center().add(loginButton).add(cancelButton);
}


It was such a simple task to develop for other such screens as well

5. Code Samples from Experts
Swing Hacks & Filthy Rich Clients are the best books on swing written by highly credible authors. The source code that comes with these books are also excellent resources.
There are quite very nice ideas explained well for developing custom components. Source code for the both the books can be freely downloaded, but I suggest to buy the books.

These are the excellent code I re-used in my application
Pieter-Jan Savat's wonderful utility on page turning effects in swing.
Simon's flashy & bouncy effects with swing.
Hyper Link listener for handling links

6. Leveraging New JDK1.5 APIs Features:
Using new JDK1.5 features can simplify the coding to great levels; JDK1.5 has been one of the biggest release in java's history.
For example, now it is possible to add data to the to list like this;
List l= list("praveen","manvi","test"); using

public static List list(T... elements) {
List list = new ArrayList(elements.length);
for (T elem : elements){
list.add(elem);
}
return list;
}


These tricks will be useful especially writing Models for UI components. The above sample shows the usage of improved for() loop, generics & variable argument options.
I found this explanation good with samples.

Monday, March 05, 2007

SWING CORNER

I have been involved with development J2EE projects from past several years. As I am looking to work with a SWING project now, I wanted to collate all the information regarding the SWING that should help me refresh my SWING skills & also to help new programmer to ramp up on SWING quickly. I also wanted to use this SWING corner blog as my SWING books-marks for my future reference.So I will keep adding/editing the information here. :-)

Real time applications are best testimonials for any technology.Here are the set of real world applications for non-SWING believers.

Selected links to start with Java SWING for beginners:
wikipedia SWING Overview
Best place to start with SWING
Swing Pointers
Sun Tutorial about SWING architecture

It is always best approach to follow best SWING programmers to learn new techniques. Here is my favorite list & their blogs. All are committed SWING developers.
1. Romain Guy with amazing swing skills
2. Ethan Nicholas
3. Kirill Grouchnikov & http://www.curious-creature.org/
4. Shannon Hickey
One more interesting Blog

There are also equally credible people saying Java SWING has reached it's dead end :-( like Bruce Eckel of Thinking Java fame, So it is equally important to watch the Adobe Flex APIs & Flash. Also there is lot of effort is being put on developing JSF components. After looking into exadel , GWT & ICE Faces I feel like do we really need thick clients?

Some Useful Java Links that will be helpful for new development:
Lot of links Articles,Blog Posts,Interviews Commercial/Open Source Projects reated to dektop development
Libraries that can ease development effort
Great Swing Components from Swing labs
Popular layout managers (Gridbaglayout has been very un-popular & difficult to work)
FormLayout
TableLayout
JGoodies Validation https://validation.dev.java.net
JGoodies Binding https://binding.dev.java.net
Spin http://spin.sf.net
Foxtrot http://foxtrot.sf.net
Swing Code samples http://www.codeguru.com/java/Swing/index.shtml
Chart building solution for swing : http://www.jfree.org/jfreechart/ - Google AdWords & Jasper Reports uses these APIs

SWING Books & Frameworks:
Popularity of any technology can also be measured from the dedicated books that have been published, Considerably there are less books focusing completely on SWING, although most of Java generic books covers SWING superficially.

There are two books published by Orielly on SWING (Hacking Swing & Java SWING ) & both are good ones, There is one book from Manning publisher Swing in Action & there is also Desktop Java Live—published by SourceBeat.
USefulness of these books are limited as it will be totally API driven & time bound, the sample source code can be downloaded from the provided by these books & learn APIs by going though the code.I guess that's the best way.The cooper's book on Design patterns contains the design pattern samples developed in SWING. The book & source code are free & can be downloaded from here.

The single-most important point to choose Java as development platform for me is availability of massive amount of open source frameworks & utilities. I guess this point is not well appreciated by well known Java opponents Joel& Paul Graham (Although they are on my favorite writers list :-)). Unfortunately there are less number of frameworks & re-usable components in SWING compared web part of java (Tag libraries, JSF components, Library utilities & MVC frameworks)
But these are few attempts in that direction, basically these frameworks tries to come up with configurable action handling, form validation, custom UI components built over standard JFC components, Custom layout managers to ease out component layering & lot of static utilities for handling validation & threading issues.

http://www.artima.com/lejava/articles/swingframework.html
http://carbonfive.sourceforge.net/springadapter/api/com/carbonfive/flash/spring/package-summary.html#documentation
Spring Rich Client - As usual Spring efforts here also are very singificant in reducing source code lines which is very important in the SWING context
"Spring makes heavy use of the "Inversion of Control" (IoC) design pattern, meaning simply that individual JavaBeans don't go looking for data, the data is handed to them by the framework"

Some important Concepts:

1. Understanding lightweight architecture
Each heavyweight component contains its own z-order layer (the notion of depth of layering) all lightweight components are inside heavyweight components and maintain their own layering scheme defined by Swing.when a heavyweight inside another heavyweight container is placed it will, by definition overlap all lightweights in that container.we have to use mixing of AWT and SWING components cautiously

-A lightweight does not contain the native code (JNI), You don't have call "System.loadLibraty()" & hence inherently cross-platform, there are may off the shelf compoenents providing different Skins (Look and Feel Factory)
-A lightweight component can have transparent pixels; a heavyweight is always opaque.
-A lightweight component can appear to be non-rectangular because of its ability to set transparent areas; a heavyweight can only be rectangular.
-Mouse events on a lightweight component fall through to its parent; mouse events on a heavyweight component do not fall through to its parent.
-When a lightweight component overlaps a heavyweight component, the heavyweight component is always on top, regardless of the relative z-order of the two components.
-JFrame , JDialog, JApplet,JWindow are the top level components & hence extend AWT compoenent instead of JComponent unlike other components

A Swing component does NOT have a corresponding native OS GUI 'peer', and is free to render itself in any way that is possible with the graphics APIs.However, at its core, every Swing component relies on an AWT container, since (Swing's) JComponent extends (AWT's) Container. AWTEvent root event class for all AWT events & there is no JVM from Sun that uses full HW acceleration, and it SHOWS. Java 5 has *partial* HW acceleration - although significantly more than java 1.4 had

2. Understand the layout managers,data binding & validation well

3. Understand Good coding practices w.r.t. Swing.
Follow the open source code (As per the list above)
Written in 2000, but still good to go though http://www.oreillynet.com/pub/a/oreilly/java/news/learningjava_0500.html

There has been quite lot of work on SWING (Now unfortunately it looks like Sun also started loosing interest in pushing Java in Desktop arena, It is now left for Open source hacker to push SWING to next level) Swing classes contributed heavily to the exponential growth of total number of java classes as part of JDK.JFC has got solid framework & design.
Total # of Java Files as of now stands at
JDK1.4 : 3,883
JDK1.5 : 6,558
JDK1.6 : 7,061


As a SWING proponent (With vested interest :-) as of now), I tried to find some answers for the current stated SWING problems

A. SWING is very slow compared to SWT.
IntelliJ-IDEA (Swing) is faster than Eclipse IDEA and Eclipse have matching complexity, and despite Eclipse is backed by IBM and open source. it still does not perform better than IDEA, which is proprietary and developed by small group of smart individuals.
Java IDE's like netbeans, Weblogic Workshop & JBuilder are written in SWING.
So it's all about how well we understand & write the code.

B. SWING solutions have very bad distribution model (With lot of confusing JREs)
I guess Sun is working hard to improve the Webstart & I hope it will be as simple as Flash plug-in (Both in terms of size and ease of use)

3. SWING is complex to work with
I guess with proper usage of scripting (Like F3, Groovy solutions) & XML should make the life simpler

Hope this blog will be useful for new as well as old SWING developers. :-)
Bookmark and Share