Archive for the java Category

Madness started at 9 p.m. – Android .. TADAAAA !

Posted in Android, Google, java, SWT, Uncategorized with tags , , , , , , on July 5, 2011 by javaforweb

Midnight madness ……  started at 9 p.m. to install Android and launch a sample application !

It all started with installing pandora on my android and as usual itching started…

Quickly installed mamoth size Android SDK… let me check the size….   2.39 GB with plugins…

After that installed ADT on eclipse and associated sdk with the project…   fetched a sample application JetBoy in to workspace…

There was a lil time consumption in adding AVD to project

Finally got success after adding third part Add-ons

Got help from

http://developer.android.com/guide/developing/devices/managing-avds.html

And launched JetBoy.java

It is a game app….  Lost badly 🙂

Now I am happy… this weekend ends in a good way….  its 12:43 a.m. and a curious mind is fed aptly ! its a good start and in coming days postmortem of Android SDK will start !

Happy to see console

[2011-07-04 23:47:24 - com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper] Unable to read C:\AndroidManifest.xml: java.io.FileNotFoundException: C:\AndroidManifest.xml (The system cannot find the file specified)
[2011-07-04 23:47:24 - com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper] Unable to read C:\AndroidManifest.xml: java.io.FileNotFoundException: C:\AndroidManifest.xml (The system cannot find the file specified)
[2011-07-04 23:52:11 - JetBoy] ------------------------------
[2011-07-04 23:52:11 - JetBoy] Android Launch!
[2011-07-04 23:52:11 - JetBoy] adb is running normally.
[2011-07-04 23:52:11 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-04 23:52:11 - JetBoy] Failed to find an AVD compatible with target 'Android 1.5'.
[2011-07-04 23:53:13 - JetBoy] Still no compatible AVDs with target 'Android 1.5': Aborting launch.
[2011-07-04 23:53:13 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-04 23:53:39 - JetBoy] Launch canceled!
[2011-07-04 23:58:20 - JetBoy] ------------------------------
[2011-07-04 23:58:20 - JetBoy] Android Launch!
[2011-07-04 23:58:20 - JetBoy] adb is running normally.
[2011-07-04 23:58:20 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-04 23:58:20 - JetBoy] Failed to find an AVD compatible with target 'Android 1.5'.
[2011-07-04 23:58:42 - JetBoy] Still no compatible AVDs with target 'Android 1.5': Aborting launch.
[2011-07-04 23:58:42 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-04 23:58:53 - JetBoy] Launch canceled!
[2011-07-04 23:59:39 - JetBoy] ------------------------------
[2011-07-04 23:59:39 - JetBoy] Android Launch!
[2011-07-04 23:59:39 - JetBoy] adb is running normally.
[2011-07-04 23:59:39 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-05 00:00:42 - JetBoy] Launch canceled!
[2011-07-05 00:12:37 - JetBoy] ------------------------------
[2011-07-05 00:12:37 - JetBoy] Android Launch!
[2011-07-05 00:12:37 - JetBoy] adb is running normally.
[2011-07-05 00:12:37 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-05 00:12:37 - JetBoy] Failed to find an AVD compatible with target 'Android 1.5'.
[2011-07-05 00:14:22 - SDK Manager] Created AVD 'FirstTest' based on Google APIs (Google Inc.), ARM (armeabi) processor,
[2011-07-05 00:14:22 - SDK Manager] with the following hardware config:
[2011-07-05 00:14:22 - SDK Manager] hw.sdCard=yes
[2011-07-05 00:14:22 - SDK Manager] hw.lcd.density=240
[2011-07-05 00:14:22 - SDK Manager] vm.heapSize=24
[2011-07-05 00:17:11 - JetBoy] Still no compatible AVDs with target 'Android 1.5': Aborting launch.
[2011-07-05 00:17:11 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-05 00:17:14 - JetBoy] Launch canceled!
[2011-07-05 00:17:29 - JetBoy] ------------------------------
[2011-07-05 00:17:29 - JetBoy] Android Launch!
[2011-07-05 00:17:29 - JetBoy] adb is running normally.
[2011-07-05 00:17:29 - JetBoy] Performing com.example.android.jetboy.JetBoy activity launch
[2011-07-05 00:17:29 - JetBoy] Automatic Target Mode: launching new emulator with compatible AVD 'FirstTest'
[2011-07-05 00:17:29 - JetBoy] Launching a new emulator with Virtual Device 'FirstTest'
[2011-07-05 00:17:35 - JetBoy] New emulator found: emulator-5554
[2011-07-05 00:17:35 - JetBoy] Waiting for HOME ('android.process.acore') to be launched...
[2011-07-05 00:19:14 - JetBoy] HOME is up on device 'emulator-5554'
[2011-07-05 00:19:14 - JetBoy] Uploading JetBoy.apk onto device 'emulator-5554'
[2011-07-05 00:19:16 - JetBoy] Installing JetBoy.apk...
[2011-07-05 00:20:25 - JetBoy] Success!
[2011-07-05 00:20:25 - JetBoy] Starting activity com.example.android.jetboy.JetBoy on device emulator-5554
[2011-07-05 00:20:30 - JetBoy] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.android.jetboy/.JetBoy }
Few useful links to start with :-
http://www.talkandroid.com/android-sdk-install-guide/
other tabs I closed :(
Have to sleep now.. Tomorrow have to get back to my Manual Testing task !
And the Song I listen to all this time is
Walk Away - Five Fingers
Just walk away make it easy on yourself, 
Just walk away please release me from this hell, 
Just walk away there's just nothing left to feel, 
Just walk away pretend that none of this is real !

Singletons in Java

Posted in Design Patterns In Java, java with tags on May 19, 2008 by javaforweb

A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive – after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can’t be instantiated by developers – meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) – by prevent direct instantiation we can ensure that developers don’t create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance – a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn’t always be acted upon. I’m sure you can think of a other situations where a singleton would be useful – perhaps you’ve even used one before without giving it a name. It’s a common enough design criteria (not used everyday, but you’ll come across it from time to time). The singleton pattern can be applied in any language, but since we’re all Java programmers here (if you’re not, shame!) let’s look at how to implement the pattern using Java.

Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let’s go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class’s constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can’t create a new instance.

We’ll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you’re free to add some initialization code if you’d like. 

public class SingletonObject
{
	private SingletonObject()
	{
		// no code req'd
	}
}

So far so good. But unless we add some further code, there’ll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn’t allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null)
          // it's ok, we can call this constructor
          ref = new SingletonObject();
      return ref;
    }

    private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world.

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don’t cause problems, so it’s advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
	 SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well…. not quite. Where there’s a will, there’s a way – it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here’s where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
	public static void main(String args[])
	  throws Exception
	{
	  // Get a singleton
	  SingletonObject obj = 
	  SingletonObject.getSingletonObject();

	  // Buahahaha. Let's clone the object
	  SingletonObject clone = 
		(SingletonObject) obj.clone();
	}
}

Okay, we’re cheating a little here. There isn’t a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton.  So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here’s the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
  private SingletonObject()
  {
    // no code req'd
  }

  public static SingletonObject getSingletonObject()
  {
    if (ref == null)
        // it's ok, we can call this constructor
        ref = new SingletonObject();		
    return ref;
  }

  public Object clone()
	throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

  private static SingletonObject ref;
}
Java Tutorials by Ashutosh Sharma, pls visit :
http://sharma.ashutosh84.googlepages.com

Final Class in Java

Posted in java with tags on May 19, 2008 by javaforweb

In Java, a class organization such as:

        class A {}

        class B extends A {}

results in a superclass (A) and a subclass (B). References to B objects may be assigned to A references, and if an A reference “really” refers to a B, then B’s methods will be called in preference to A’s. All of this is a standard part of the object-oriented programming paradigm offered by Java.

But there is a way to modify this type of organization, by declaring a class to be final. If I say:

        final class A {}

then that means that A cannot be further extended or subclassed.

This feature has a couple of big implications. One is that it allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior. For example, java.lang.String is a final class. This means, for example, that I can’t subclass String and provide my own length() method that does something very different from returning the string length.

There is also a big performance issue with final classes. If a class is final, then all of its methods are implicitly final as well, that is, the method is guaranteed not be overridden in any subclass. A Java compiler may be able to inline a final method. For example, this program:

        final class A {
                private int type;
                public int getType() {return type;}
        }

        public class test {
                public static void main(String args[])
                {
                        int N = 5000000;
                        int i = N;
                        int t = 0;
                        A aref = new A();
                        while (i-- > 0)
                                t = aref.getType();
                }
        }

runs about twice as fast when the class is declared final.

Of course, much of the time it’s desirable to use the superclass / subclass paradigm to the full, and not worry about wringing out the last bit of speed. But sometimes you have heavily used methods that you’d like to have expanded inline, and a final class is one way of achieving that.

Java Tutorials by Ashutosh Sharma :

pls visit http://sharma.ashutosh84.googlepages.com

Sun’s Strategy On JavaFX, Ready to take on Adobe AIR & Silverlight

Posted in java, JavaOne 2008, Web 2.0 with tags , on May 17, 2008 by javaforweb

At Java One last week Sun sold its year-old-but-still-upcoming – and definitely late-to-the-party – Adobe AIR- and Microsoft Silverlight-competitive JavaFX Rich Client environment as a potential revenue-generator capable of putting ads on mobile applications and JavaFX Script, its newfangled high-performance GUI declarative scripting language, as the way to build consumer next-generation RIAs for desktops, mobiles, TV and other consumer devices.

Otherwise developers are – preferably – supposed to use the NetBeans IDE to write JavaFX apps, which are supposed to move effortlessly from device to device. FX has its own runtime and media codec framework.

Sun is promising JavaFX Desktop for browsers and PCs this fall and JavaFX TV and the previously announced JavaFX Mobile next spring. It says it’ll have a preview of the JavaFX Desktop SDK this summer.

It’s got demos at www.javafx.com , also to see Java FX Master work visit www.teslamotors.com

Something like 85% of cell phones (like Google’s Android), 91% of desktops, and all Blu-ray disc players are supposed to be able to run JavaFX.

It’s also promising the stuff will be cloud-borne.

Sun says it’s got two projects the other side of JavaFX. One, called Hydrazine, is supposed to let content creators find information and services in the cloud, merge those services together, deploy them in the cloud and share them.

And the other, called Project Insight, is supposed to let developers track how their applications are being used and who’s using them so they can be monetized with advertising. Sun is planning on monetizing that one itself.

Vector vs ArrayList

Posted in java with tags on May 14, 2008 by javaforweb

 

The three implementations of the List interface are Vector, ArrayList and Linked List.

 

Vector and ArrayList both of these classes are implemented using dynamically resizable

arrays.

 

Vector class is Thread-Safe.

 

Which one you should choose will depend on the requirements of your implementation.

An ArrayList is very efficient for getting objects from the list.

 

The LinkedList is more efficient at insertions into and deletions from the list.

It also performed very well at iterating through the list.

 

The Vector performed worst of all 3 List objects.

The Vector class is less efficient than the ArrayList class mainly because the Vector class

is synchronized

 

 

When multiple threads share the same instance of Vector, then that

instance can be subject to manipulation by both threads without any inconsistency in results.

i.e.,Access to shared data within the Vector is synchronous..One follows the other.

 

Vectors are a lot slower, performance wise, than ArrayLists.

So, my rule is to use Arraylists unless you need synchronised lists.

 

And one more advantage with this Array List is that it belongs to the re-engineered version

of util package, so it has the compatability with the Collections class where you can convert

into various data structures..

 

ArrayList is not synchronized by default –

although the collections framework provides wrappers to provide thread safety when needed.

 

 

For some of the latest JVMs the difference in speed between the two classes is negligible:

strictly speaking, for these JVMs the difference in speed between the two classes is less

than the variation in times obtained from tests comparing the performance of these classes.

 

To visualize the problem with synchronization, try the following code.

 

There is a Producer class that adds 5000 elements to the List (ArrayList/Vector).

Another class, Consumer class removes 5000 elements from the same list.

There are around 10 producer threads and 10 consumer threads.

import java.util.*;

class Producer implements Runnable {

 

private List list;

 

public Producer(List pList) {

list = pList;

}

 

public void run() {

System.out.println(“Producer started”);

for (int i = 0; i < 5000; i++) {

list.add(Integer.toString(i));

}

System.out.println(“Producer completed”);

}

 

}

 

 

import java.util.*;

class Consumer implements Runnable {

private List list;

 

public Consumer(List pList) {

list = pList;

}

 

public void run() {

System.out.println(“Consumer started”);

for (int i = 0; i < 5000; i++) {

while (!list.remove(Integer.toString(i))) {

// Just iterating till an element is removed

}

 

}

System.out.println(“Consumer completed”);

}

}

 

 

import java.util.*;

public class ListTest {

 

public static void main(String[] args) throws InterruptedException {

//List list = new Vector();

List list = new ArrayList();

 

for (int i = 0; i < 10; i++) {

Thread p1 = new Thread(new Producer(list));

p1.start();

}

 

for (int i = 0; i < 10; i++) {

Thread c1 = new Thread(new Consumer(list));

c1.start();

}

Thread.yield();

 

while (Thread.activeCount() > 1) {

Thread.sleep(100);

}

 

System.out.println(list.size());

 

}

 

}

 

 

 

 

Try running the program with ArrayList.

You can see a number of ArrayIndexOutOfBoundException,

Consumer threads will still keep waiting for more elements which wont be added because the

Producer has terminated after throwing the Exception.

 

Now, change the line,

 

List list = new ArrayList();

to

List list = new Vector();

 

Now you can see a proper result.

 

This clearly explains why you should use Vector class when there are multiple threads in the system.

 

In this program, even if you remove the Consumer class and Consumer thread, you can see that the

Producer will themselves throw Exception.

 

This is because, while adding an element to the ArrayList, it checks for the size of the Array.

If the array size is not sufficient, a new array will be created, the elements will be copied to

the new array. If the context switching if Threads happen at this place also, we will get

ArrayIndexOutOfBoundException, or sometimes, you maynot get any Exception, but some elements will

be missing, and many unexpected behaviours.

 

So always use Vector if there are multiple threads. The same rule applies to

HashMap vs Hashtable, StringBuilder vs StringBuffer

 

For Best Java Tutorials Please Visit :

http://sharma.ashutosh84.googlepages.com

Serializing Objects in Java

Posted in java with tags on May 6, 2008 by javaforweb

Adding object persistence to Java applications using serialization is easy. Serialization allows you to save the current state of an object to a container, typically a file. At some later time, you can retrieve the saved data values and create an equivalent object. Depending on which interface you implement, you can choose to have the object and all its referenced objects saved and restored automatically, or you can specify which fields should be saved and restored. Java also provides several ways of protecting sensitive data in a serialized object, so objects loaded from a serialized representation should prove no less secure than those classes loaded at application startup. Versioning provides a measure of the backward compatibility of class versions. The code needed to add serialization to your application is simple and flexible.

Code

The following code illustrates the writing and reading of Serializable and Externalizable classes. ObjectReaderWriter is the primary application class. At runtime it displays a “Save As…” FileDialog, allowing you to specify an output file to receive the stream containing the serialized objects. (All the sample objects are written to the same file.) It then prompts for an input file from which to read a stream.

This arrangement of the sample code allows you to write out the serialized data to one file, make changes to the class format for one or more of the data classes, recompile and rerun, and attempt to read one of the older versions back in.

The class MySerialObject contains a reference to an instance of the class MyInternalObject, to demonstrate the saving of nested object references in the stream. MySerialObject also contains a field (of type int) that is marked transient, and upon restoration you will find that the default value 0 gets assigned to that variable.

The class MyVersionObject demonstrates the use of versioning with a programmer-specified SUID. You only need to change the SUID when you make changes to the class structure that render it incompatible with older versions of that same class, and whose serialized instances have previously been written to disk.

You can compile the .java (source) files using the javac (Java compiler) tool or simply using javac Utility.You can then optionally create a .jar (Java archive) file containing the resulting .class (output) files.

Main Java Class:  ObjectReaderWriter.java

import java.awt.*;
import java.io.*;

public class ObjectReaderWriter {
  String filePath;

  public static void main( String args[] ) {
    ObjectReaderWriter orw = new ObjectReaderWriter();
  }

  ObjectReaderWriter() {
    try {
      //  Create instances of each data class to be serialized.
      MySerialObject serialObject = new MySerialObject();

      MyExternObject externObject = new MyExternObject();

      MyVersionObject versionObject = new MyVersionObject();

      //  Allow the user to specify an output file.
      FileDialog fd = new FileDialog( new Frame(),
        “Save As…”, FileDialog.SAVE );
      fd.show();
      filePath = new String( fd.getDirectory() + fd.getFile() );

      //  Create a stream for writing.
      FileOutputStream fos = new FileOutputStream( filePath );

      //  Next, create an object that can write to that file.
      ObjectOutputStream outStream =
        new ObjectOutputStream( fos );

      //  Save each object.
      outStream.writeObject( serialObject );

      externObject.writeExternal( outStream );

      outStream.writeObject( versionObject );

      //  Finally, we call the flush() method for our object, which
      //    forces the data to
      //  get written to the stream:
      outStream.flush();

      //  Allow the user to specify an input file.
      fd = new FileDialog( new Frame(), “Open…”,
          FileDialog.LOAD );
      fd.show();
      filePath = new String( fd.getDirectory() + fd.getFile() );

      //  Create a stream for reading.
      FileInputStream fis = new FileInputStream( filePath );

      //  Next, create an object that can read from that file.
      ObjectInputStream inStream = new ObjectInputStream( fis );

      // Retrieve the Serializable object.
      serialObject = ( MySerialObject )inStream.readObject();

      //  Display what we retrieved:
      System.out.println( serialObject.getS() );
      System.out.println( “i = ” + serialObject.getI() );
      serialObject.displayInternalObjectAttrs();

      // Retrieve the Externalizable object.
      externObject.readExternal( inStream );

      //  Display what we retrieved:
      System.out.println( externObject.getS() );
      System.out.println( “i = ” + externObject.getI() );

      // Retrieve the versioned object.
      versionObject = ( MyVersionObject )
        inStream.readObject();
      //  Display what we retrieved:
      System.out.println( versionObject.getS() );
      System.out.println( “i = ” + versionObject.getI() );

      // Display the SUID of the versioned class in the VM,
      // not necessarily the serialized object.
      ObjectStreamClass myObject = ObjectStreamClass.lookup(
          Class.forName( “MyVersionObject” ) );
      long theSUID = myObject.getSerialVersionUID();

      System.out.println
        ( “The SUID of class MyVersionObject = ” + theSUID );
    }
    catch ( InvalidClassException e ) {
      System.out.println( “InvalidClassException…” );
    }
    catch ( ClassNotFoundException e ) {
      System.out.println( “ClassNotFoundException…” );
    }
    catch ( OptionalDataException e ) {
      System.out.println( “OptionalDataException…” );
    }
    catch ( FileNotFoundException e ) {
      System.out.println( “FileNotFoundException…” );
    }
    catch ( IOException e ) {
      System.out.println( “IOException…” );
    }
  }
}

MySerialObject.java

MySerialObject.java
The serializable data class.

import java.io.*;

public class MySerialObject implements Serializable {
  private transient int i;
  private String s;
  MyInternalObject mio;

  MySerialObject() {
    i = 64;
    s = new String( "Instance of MySerialObject..." );
    mio = new MyInternalObject();
  }

  public int getI() {
    return i;
  }

  public String getS() {
    return s;
  }

  public void displayInternalObjectAttrs() {
    System.out.println( mio.getS() );
    System.out.println( "i = " + mio.getI() );
  }
}

Listing 3: MyInternalObject.java

MyInternalObject.java
The nested data class.

import java.io.*;

public class MyInternalObject implements Serializable {
  private int i;
  private String s;

  MyInternalObject() {
    i = 128;
    s = new String( "Instance of MyInternalObject..." );
  }
  public int getI() {
    return i;
  }

  public String getS() {
    return s;
  }
}

Listing 4: MyExternObject.java

MyExternObject.java
The externalizable data class.

import java.io.*;

public class MyExternObject implements Externalizable {
  private int i;
  private String s;

  MyExternObject() {
    i = 256;
    s = new String( "Instance of MyExternObject..." );
  }

  public int getI() {
    return i;
  }

  public String getS() {
    return s;
  }

  public void writeExternal( ObjectOutput out ) throws
      IOException {
    out.writeInt( this.i );
    out.writeObject( this.s );
  }

  public void readExternal( ObjectInput in ) throws
      IOException, ClassNotFoundException {
    this.i = in.readInt();
    this.s = ( String )in.readObject();
  }
}

Listing 5: MyVersionObject.java

MyVersionObject.java
The versioned data class.

import java.io.*;

public class MyVersionObject implements Serializable {
  static final long serialVersionUID = 1L;
  private int i;
  private String s;

  //  Uncomment the next two lines to verify that default values will be substituted if
  //  the value is not present in the stream at deserialization time.
  //  private int i2 = -1; private String s2 = "This is the new String field";

  MyVersionObject() {
    i = 512;
    s = new String( "Instance of MyVersionObject..." );
  }

  public int getI() {
    return i;
  }

  public String getS() {
    return s;
  }
}

Nimbus – A New Look-and-Feel for Swing

Posted in java with tags on May 5, 2008 by javaforweb

Nimbus is the name of a look-and-feel designed by Sun for the Java Desktop System; it’s implemented as a GTK theme in the latest Solaris 11 pre-release builds. In 2007, this project was started by Sun’s Swing Team and Ben Galbraith to build a pure Java implementation of this look and feel under a opensource licence. Later on it was decided to pull Nimbus LAF in to the core of the Java platform as part of version 6u10. Nimbus is now available in the beta version of 6u10 available at http://download.java.net/jdk6/.

The version in the JDK took some of the concepts that were experimented with in the project but is a complete new codebase. It is still based on Synth LAF but is 100% pure vector based using no images. This project is dead for the time being until Nimbus is made opensource through Open JDK. Once that happens it might be pulled back into the project so that we can work on a backport jar that could run on older Java versions than 6u10.

Nimbus is a new cross-platform Swing look & feel, which packs many features and enhancements. It is not just another look and feel but with some exciting features:

2D Vector
All of Nimbus is rendered with 2D vector graphics, there is not one image even for all the icons. This means that the whole of Nimbus is just 56k as a packed JAR which is pretty impressive for a whole rich look and feel.
High DPI Ready
As the whole of Nimbus is drawn with shapes and gradients it can be scaled to any resolution.
Based on Painters
All painting for components is done with simple stateless implementations of the Painter interface. These painters are stored in the UIDefaults table so they can be replaced if you would like to change the look of components or can be used in your own components if you would like to create a custom table header for example that looks the same as the standard Nimbus one plus something extra.
Customizable
All colors, icons and fonts are derived off UIDefaults keys so the whole UI can be customized by changing values in the UIDefaults table.
Easy to skin 3rd party components to fit in
All of the colors, fonts, icons, borders and painters are exposed through the UIDefaults table which means they are available to your 3rd party components to help you skin them in a Nimbus style.

Usage

To use the Nimbus Look & Feel, simply call the setLookAndFeel methods from UIManager:

        try {
            UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }

Alternatively, you can either specify the L&F from swing.properties file or from a command line. To use the swing.properties files, specify the swing.defaultlaf property. The file (if exists) is located under <jre install>\lib:

# Swing properties
swing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

To specify the L&F from command line, use the following when running your Java application:

-Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel