Tuesday, December 30, 2008

Z-Order is supported in JavaFX !

While writing some of the samples in which we have to play with images, we sometimes has to manage the depth of the images. Like for the Carousel example, every image has a depth. In that example, actually images are not overlapping with each other, so we never need to write the Z-Order concept. But if someone want to write a Carousel or some application in which Images are residing over other images, we need to set the Z-order of Images. Z-Order in literal term means depth-ness of images. JavaFX gracefully provide API's to set the Z-order of images. With a simple call, you can set the images toFront or toBack features.


In this example, I have taken 3 images and try to set the depth-ness of images on the event of Buttons.



First Image on Top Second Image on Top





Third Image on Top


Here is the code to set the Z-Order :


package zorder;

import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.input.MouseEvent;
import javafx.ext.swing.SwingButton;

var im1 = ImageView {
x: 100
y: 100
image: Image {
url: "{__DIR__}im1.PNG"
}
opacity: 0.8
};

var im2 = ImageView {
x: 130
y: 130
image: Image {
url: "{__DIR__}im2.PNG"
}
opacity: 0.8
};

var im3 = ImageView {
x: 160
y: 160
image: Image {
url: "{__DIR__}im3.PNG"
}
opacity: 0.8
};

var gp = Group {
content:[
im1, im2,im3
]

}
Stage {
title: "Application title"
width: 400
height: 400
scene: Scene {
fill: Color.BLACK
content: [
gp,
SwingButton {
translateX: 10
translateY: 10
text: "Image 1"
action: function() {
im1.toFront();
}
}
SwingButton {
translateX: 90
translateY: 10
text: "Image 2"
action: function() {
im2.toFront();
}
}
SwingButton {
translateX: 170
translateY: 10
text: "Image 3"
action: function() {
im3.toFront();
}
}
]
}
}




From next blog, I will use applet or JNLP in place of images, as suggested by Dmitry in last blog. Pictures make it bulky and uneasy to load. But I was getting some problem in deploying the application on Sun blog which will be rectified soon.

Monday, December 22, 2008

JavaFX production Suite - How it work

Here is the little discussion on Designer + Developer workflow in JavaFX. Powered with Project Nile, we can export data from PhotoShop or Illustrator. Actually the complete production suite is awesome and provide developer and designer to work in parallel. Here how it is :



So, Developer can work on the business logic and till that time designer can design the actually content for developer. Finally it will merge in a great style. 


 Basic Requirement to do :


1. JavaFX Production Suite : Download from the start section of javafx.com.


2. For Designer : Any tool, either PhotoShop CS3 or Illustrator CS3. Officially CS3 is the supported platform but it works for CS4 as well.


3. For Developer : Java FX SDK: Download from the start section of javafx.com


Now, I am going ahead with PhotoShop. Copy the plugin from JavaFX production suite to PhotoShop. Run the PhotoShop, in export it will give you a save option in JavaFX, which basically saves the file in fxz format(a new format, why Sun need a new format, there is a lot of discussion and Jeet has pointed some reason in his blog).


Alright, so work started : 


I was watching the batman movie, so decide to take his awesome car, which is here :





In photoshop, I have changed the hue and exported all in fxz format.


Then I made a Netbeans Project, Copy the fxz file into the project space. We can now click on fxz file, we can see the preview and code as well. Right now, if we put some of the complex features of PhotoShop, I am afaird to say JavaFX will not catch those changes.


So, my fxz file(JavaFX.fxz) looks like this :


  /*
 * Generated by JavaFX plugin for Adobe Photoshop.
 * Created on Fri Dec 19 19:17:33 2008
 */
//@version 1.0

Group {
    clip: Rectangle { x:0 y:0 width:576 height:432 }
    content: [
        ImageView {
            opacity: 1.0
            x: 0
            y: 0
            image: Image {
                url: "{__DIR__}Background.png"
            },
        },
    ]
}

Actually in my case there was nothing, so it generated a simple code :).


Now, I have made another file, calling it CarRotate.fx :



package psfx;

import java.lang.*;
import javafx.fxd.FXDLoader;
import javafx.scene.*;
import javafx.scene.input.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.*;


var group = Group {
    content: []
};
var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content
insert fxdContent into group.content; // inserts the fxd content into the group


Stage {
    title: "JavaFX Invaders"
    resizable: true
    width: 700
    height: 700
    onClose: function() {
        System.exit (0);

    }
    scene: Scene {
        content: [
            group
            Rectangle {
                x: 330,
                y: 500
                width: 60,
                height: 30
                fill: Color.GRAY
                onMouseClicked: function( e: MouseEvent ):Void {
                    fxdContent.rotate = 90;
                }
            }
        ]
    }
};



Some part of the code is point of interest :







  var group = Group {

    content: []

};

var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content

insert fxdContent into group.content; // inserts the fxd content into the group



Here I have loaded the .fxz file into var fxdContent which is a node and node means things are in our hand. I have simply written a rotate equation on a button click which is working nicely.




We can see the rotated car and hue which is the asset of PhotoShop in Green color. Huh, finally its done. Sorry, for posting bad example.

JavaFX - Developer and Designer work !

One more example of JavaFX production Suite. Though the complete thing can be done in Photoshop alone but I am just giving an example. I have made a house in Photoshop, which is not very good :(, but fair enough. And I animated the star effect in JavaFX.


So, here is my home in photoshop :



Actually this is funny, I was following a tutorial to make house and in temptation, I made shadow as well, but there is no meaning of shadow in night :). Now, I filled star sparking effect in this from JavaFX.




Filling star effect need same which we have written for sparkling glasses. Just some changes here and there. In the last blog we have already discussed how to import work from Photoshop.

Here are the things to download:

1. House in fxz format .

2. Code (Main.fx, Star.fx)

Lot many things can be done. But I don't know Photoshop.

Wednesday, December 10, 2008

Physics Motion - Spring In JavaFX

3 weeks back, we were thinking of some cool application to make. I am a guy who has seen very less outside world, so coming up with some great idea is always tough for me. So, deciding that, I went back to my tenth class physics book and saw some of the cool physics motion. Its one of the tough subject and always screw me in exam. Searching some of the easy equation, I though to make one spring motion. Meantime, I though there is some spring motion residing in our repository. Actually one of the Josh applications do it in awesome way, but still we were missing the actual feel of Spring motion because of the gig-gag and spiral stuff attached to the wall and spring is going up and down in it, with a complete view of awesomeness :). This is what finally we achieve from this blog :



I can still bet this can be 3 times much better than what you are seeing here. So, little of good news here that this sample can be executed on mobile



Regret to say, ball will not look like a real 3D ball in FX Mobile because of Bug ID: RT-2205, which basically speaks that Mobile Runtime don't understand Radial Gradient, hoping this will be fixed soon.

Here are the code files :

1. Main file.

2. Spring file.

3. SpringEquation file.

Enjoy FX'ing !

Tuesday, December 09, 2008

3D E'FX's in JavaFX

Me and Vikram was looking today some of the cool flash examples and I have seen the button effect at some place, when you press the button it really goes like inside and coming out. But that was an effect achieved by the images(two different images, one unpressed button and one pressed button) and then we thought to simulate this effect by code. Somehow we are able to do that in FX, here is the final outcome:




What we have tried to do is pressing one button will put the other in unpressed mode and vice-versa. This has been achieved by some of the cool API's of JavaFX. And we have used the DistantLight effect of JavaFX which gives a lighting effect in its awesome way. Actually this can be more cooler but I left that for developer to modify it according to their need :). But this is a modular code and can be used in any of the button place.


Here is the simple code for the same(again code is not written in the most optimized way but in the best way for understanding) :



package lighteff;

import javafx.scene.effect.light.DistantLight;
import javafx.scene.effect.Lighting;
import javafx.scene.Group;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

var factor = 5;
var scale = 1.0;
var factor1 = 10;
var scale1 = 0.85;

Stage {
title: "Control Panel"
width: 290
height: 180
style: StageStyle.UNDECORATED
scene: Scene {
fill: Color.BLACK
content: [
Group {
effect: Lighting {
light: DistantLight {
azimuth: 90
elevation: 60
}
surfaceScale: bind factor
}
content: [
Circle {
centerX: 100,
centerY: 100
radius: 40
fill: Color.RED


onMousePressed: function( e: MouseEvent ):Void {
scale = 0.85;
factor = 10;
scale1 = 1.0;
factor1 = 5;
}
},
Text {
fill: Color.WHITE
scaleX: bind scale
scaleY: bind scale
font: Font {
size: 24
}
x: 71,
y: 105
content: "Press"
}
]
},
Group {
effect: Lighting {
light: DistantLight {
azimuth: 90
elevation: 60
}
surfaceScale: bind factor1
}
content: [

Circle {
centerX: 200
centerY: 100
radius: 40
fill: Color.BLUE
onMousePressed: function( e: MouseEvent ):Void {
scale1 = 0.85;
factor1 = 10;
scale = 1.0;
factor = 5;
}
},
Text {
fill: Color.WHITE
scaleX: bind scale1
scaleY: bind scale1
font: Font {
size: 24
}
x: 171,
y: 105
content: "Press"
}
]
}
]

}
}

Monday, December 01, 2008

Java Plugin2 - Docs !


With Plug-in 2(Java 6u10), a whole new experience comes into Java Plug-in. I have mentioned the new features of Plugin2 in some of my presentations of 6u10.


For detail, please visit this link : http://java.sun.com/javase/6/webnotes/6u10/plugin2/index.html


Switching between old/new plugin:


Java Control Panel - Advanced - Java Plug-in - Enable the next gen plug-in.


(Check this link : http://www.java.com/en/download/help/new_plugin.xml)




By default, it will take new plugin, but untick it for old plugin.

Scene to Scene in JavaFX

Any middle or big application demands to change one window to other at some point of time. A window type of thing in JavaFX is represented by Scene and its each to switch between scene or to run multiple scenes.


Here is a small application in which clicking on image will put you in another window, written "Hello World"



package sample6;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;

var s_new:Scene;
var s = Scene {
content: [
Text {
font: Font {
size: 24
}
x: 10,
y: 30
content: "HelloWorld"
}
]
};

var s1 = Scene {
content: [
ImageView {
image: Image {
url: "{__DIR__}im2.PNG"
}
onMouseClicked: function( e: MouseEvent ):Void {
s_new = s;
}
}
]
};

s_new = s1;
Stage {
title: "Application title"
width: 250
height: 280
scene: bind s_new
}

So, its simple, on mouse click, I have bind a scene variable with a new scene. That's it !



Moving image from MouseDrag

So, we got a discussion here. Last week we(me, Subrata and Vikram, both my office colleagues) are discussing about dragging an image with mouse pointer in JavaFX.


So, this was the first code. Point is to drag an image from the same place where we first hit the mouse, like it happens when we drag a folder :




package sample5;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import java.lang.System;

var x: Number;
var y: Number;

var im = Image {
url: "{__DIR__}im2.PNG"
};

var temp1:Number = 0;
var temp2: Number = 0;
var count: Integer = 1;
Stage {
title: "Application title"
width: 250
height: 280
scene: Scene {
content: [
ImageView {
x: bind x - temp1
y: bind y - temp2
image: Image {
url: "{__DIR__}im2.PNG"
}
onMouseDragged: function( e: MouseEvent ):Void {
x = e.x;
y = e.y;
if(count <= 1) {
temp1 = e.x;
temp2 = e.y;
}
count++;
}
}
]

}
}





You can see those patches of counts and flags which makes the code so unstable. And a bug, when you leave the mouse once, it cant grip the image from your mouse point again.





Subrata has written a cleaner code which works correct and here it is :


 
package mousedrag;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;

/**
* @author Subrata Nath
*/

var imgX : Number = 20;
var imgY : Number = 20;
var startX : Number;
var startY : Number ;
var distX : Number;
var distY : Number ;

Stage {
title: "Mouse smooth drag"
width: 250
height: 280
scene: Scene {
content: [
ImageView {
x : bind imgX

y : bind imgY
image: Image {url: "{__DIR__}Mail.png"
}
onMousePressed: function( e: MouseEvent ):Void {
startX = e.x;

startY = e.y;
// Calculate the distance of the mouse point from the image top-left corner
// which will always come out as positive value
distX = startX - imgX;

distY = startY - imgY;
}
onMouseDragged: function( e: MouseEvent ):Void {
// Find out the new image postion by subtracting the distance part from the mouse point.

imgX = e.x - distX;
imgY = e.y - distY;
}
}
]

}
}









Sparkling Glass

What to achieve: A sparkling glass(beer glasses are clean and shiny before beer get served) like this.



So, our aim is to make those sparkling effect on glass. Here is the code in JavaFX(things are little hard coded but better for understanding):


 
package sample;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseEvent;
import javafx.scene.transform.Rotate;
import javafx.scene.shape.Polygon;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Interpolator;
import javafx.scene.shape.Circle;
import javafx.scene.Group;
/**
* @author Vaibhav
*/

var r = 0.0;
var t = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 3s
canSkip: true
values: [
r => 360.0 tween Interpolator.EASEBOTH
]
}
]
}
t.play();
var op = 1.0;
var t1 = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
KeyFrame {
time: 3s
canSkip: true
values: [
op => 0.0 tween Interpolator.EASEBOTH
]
}
]
}
t1.play();

Stage {
title: "Sparkling on Glass"
width: 250
height: 480
scene: Scene {
fill: Color.BLACK
content: [
ImageView {
image: Image {
url: "{__DIR__}wineglass.png"
}
}
Polygon {
rotate: bind r;
translateX: 130
translateY: 100
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 130
translateY: 100
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
Polygon {
rotate: bind r;
translateX: 50
translateY: 50
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 50
translateY: 50
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
Polygon {
rotate: bind r;
translateX: 30

translateY: 120
scaleX: 0.5
scaleY: 0.5
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind op
},
Polygon {
rotate: 45;
scaleX: 0.25
scaleY: 0.25
translateX: 30
translateY: 120
points: [ 0,0, 2,-50, 4,0, 54,2,4,4,2,54,0,4,-50,2]
fill: Color.WHITE
opacity: bind 1 - op
},
]

}
}


Same animation in flash is here : http://www.entheosweb.com/Flash/sparkling_effect.asp

Java Market Trend

Today I got a mail from Carl. He works in a company which provides Marketing stats. Here are some of the exciting marketing stats of Java :


1. Median Salary :












Generated By: OdinJobs - Techonology Job Search Engine




2. Jobs Trend line













Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine



3. Salary Histogram :












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine



Now, see the market increase in Java Gaming.And there is a reason behind it, people start realizing that Java is fast and a suitable language for gaming. It happened for quite a long time developed used to think that Java is a slow language and not meant for game.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


Banking sector, this is quite obvious because of the market fall down, else it was little above than the last year performance.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


Defense: This is quite an interesting market. It speaks about the robustness and security of Java. Defense finds it the best language for their purpose.












Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


For more visit this link : Java Market Stats

Saturday, October 18, 2008

JavaFX – Getting Started


Alright, here is the blog for the beginner of JavaFX. We generally say it “getting started”

So, right now I suggest you to work with Netbeans 6.1. There is a good amount of code change going to happen soon in JavaFX but never mind. Here we go:

  1. Start Netbeans 6.1. Go into Tools -> Plugin section. Go into Available Plugins, search for JavaFX in the search box. You may see more than this, but whatever comes on the name of JavaFX, install all (I already have it in installed section).


  1. After installation, go into File -> New Project Section. You can see JavaFX now in project section:


  1. Click on Next, It will ask for Project Name. Enter a project name “JavaFXApplication” (this is what I have written) and click finish. You will get something like this:


  1. But the most important thing is what you get on right most side with a caption “Palette” (FX Builder). Here how it looks:


  1. In place of “place your code here”, we need to write our code. So, let’s start with “Drag and Drop” work. First we will make a circle. So, drag a Frame into the code space and then drag a circle in the content section of code.


  1. Before running the code, you can see the preview of output, by clicking on the preview button.


  1. This is how the preview will come:


  1. After you convince with the output, go into the Run Section. Run the application or press F6.

In the next blog, we can discuss on how to use FX builder to make more wise applications like running a ball, making 3D balls, image gallery or something else, depending on the demand :).


Please let me know if there is/are some problem(s) in installation or running the application.If you are not a netbeans user, the you have two option :

- Wise one, download netbeans and start working :).

- Unwise one, we can also work only with javafx preview developer by putting the code in bin folder compiling with javafxc and running with javafx. But then you will not be able to use lot of netbeans features.


Sunday, September 14, 2008

JavaFX Presentation

Today we had a good BOJUG meet at Thoughtworks. I have presented my small JavaFX slides. Followed to that, Sathish has given a presentation on Bean Binding and Bean Validation. He talked about JSR 295 + JSR 303. Quite a handsome presentation. After this, Sriram has taken the presentation on Tomcat internal and it seems he really went into internal. He talked about how to write own ClassLoader in tomcat + how to provide a webapps on fly, many more. It was a nice presentation without presentation slides :-).

Here is my presentation. Please feel free to comment.

Filling eyes effect in JavaFX

This is one simulation of Golden Eyes :-D(with an ugly face). I tried to make one use of Gaussian Blur which is applied in the white color of eyes. Adding this spot in the eyes gives a real simulation.



package eyes;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Arc;
import javafx.scene.geometry.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.*;
import javafx.scene.effect.*;

var y: Number = 150;
Frame {
title: "Golden Eyes"
width: 500
height: 500
closeAction: function() { java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.GRAY;
content: [

Circle {
centerX: 160, centerY: y
radius: 23
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.GOLD },
Stop { offset: 1.0 color: Color.BLACK }
]
}
opacity: 0.9
},

Circle {
centerX: 160, centerY: y
radius: 10
fill: Color.BLACK
},
Circle {
centerX: 166, centerY: y - 5
radius: 5
fill: Color.WHITE;
effect : GaussianBlur {
radius: 6
}
},
Circle {
centerX: 250, centerY: y
radius: 23
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.BLACK },
Stop { offset: 1.0 color: Color.GOLD }
]
}
opacity: 0.2
},


Circle {
centerX: 250, centerY: y
radius: 10
fill: Color.BLACK
},
Circle {
centerX: 244, centerY: y - 5
radius: 5
fill: Color.WHITE;
effect : GaussianBlur {
radius: 6
}
},
Circle {
centerX: 200, centerY: 180
radius: 100
fill: Color.SIENNA
opacity: 0.1

},
Polyline {
stroke:Color.BLACK
points: [
200,160,
220.0,220.0,
180.0,220.0
]
},
Path {
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 1.0
endY: 0.0
proportional: true
stops: [
Stop { offset: 0.0 color: Color.BLACK },
Stop { offset: 1.0 color: Color.RED }
]
}
elements: [
MoveTo { x: 160 y: 240 },
ArcTo { x: 250 y: 240 radiusX: 100 radiusY: 100},

]
},

]
}
}

Tracing the ball path in Java FX !

Alright, So now again one post for JavaFX. Finally I am able to write tracing path code in JavaFX. I have seen this in lot of Physics Motions where they show motion with tracing effect. Have a look at the output :


package tracemotion;

import javafx.scene.Node;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.scene.geometry.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;

import java.lang.System;
import java.lang.Math;

var t : Number = 0.0;

Frame {
var input : TracingBall = TracingBall {};
stage : Stage {
fill: Color.BLACK;
content : bind [
input
]
}

visible : true
title : "Tracing Ball"
width : 600
height : 600
closeAction : function() { java.lang.System.exit( 0 ); }
}

class TracingBall extends CustomNode {

attribute tracingballs : Circle[];
attribute length : Integer = 600;
attribute timer : Timeline = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames :
KeyFrame {
time : 100ms
action : function() {
update();
t = t+0.3;
}
}
}
public function update() : Void {
for( i in [0..length - 30] ) {
tracingballs[i].centerX = tracingballs[i+30].centerX;
tracingballs[i].centerY = tracingballs[i+30].centerY;
tracingballs[i].radius = tracingballs[i+30].radius;
tracingballs[i].opacity=0.4;
}
tracingballs[length] = Circle {
centerX : bind(100 + t * 30),
centerY : (300 + Math.cos(t) * 100),
radius : 30,
fill : bind LinearGradient {
proportional: true
stops: [
Stop { offset: 0.0 color: Color.RED },
Stop { offset: 1.0 color: Color.GAINSBORO },
]
},
opacity : 1.0

};
}
public function create(): Node {
return Group {
content : bind[tracingballs]
};
}
init {
for( i in [0..length] ) {
insert Circle { fill : bind LinearGradient {
proportional: true
stops: [
Stop { offset: 0.0 color: Color.RED },
Stop { offset: 1.0 color: Color.GAINSBORO },
]
},
} into tracingballs;

}
timer.start();
}
}

Some lines in code are filling those fancy colors in ball(some lines are hard coded as well).I am a real bad guy in filling nice catchy colors(this color looks like a sun and a moon combination). Any comments/improvements are welcome !

2+2=4 and so 2*2

Last week, our office celebrates OpenSource Mela. In code war, we got a programming contest in which the problem statement is :

5 * 4 / 2 - 5 + 2 = 7 (evaluated from left to right). So, input format is:

5 4 2 5 2 7

and output is to put into a valid expression format(all possible format). So, if its 2 2 4, then 2+2=4 and 2*2=4 is possible. I have written some code for this, which goes here :

package problemstatement1;

import java.util.List;

public class Main {

String input = "2 0 2";
String output = new String(); // 5 * 4 / 2 - 5 + 2 = 7
int resultVal = 0;
String operatorseq = new String();
int result = 0;
int totalcounter = 0;
boolean flag = true;

// converting input into easy format

String[] inputtoken = input.split(" ");
int[] numberseq = new int[inputtoken.length - 1];
int totaloperator = numberseq.length - 1;

public void isValid() {
if (inputtoken.length < 3) {
System.out.println("Usages ... Input Parameter should be three or more ");
System.exit(0);
}
}

public void processInput() {
try {
resultVal = Integer.parseInt(inputtoken[inputtoken.length - 1]);
} catch(NumberFormatException e) {
System.out.println("Parsing error" + " " + e);
System.exit(0);
}
for (int i = 0; i < numberseq.length; i++) {
try {
numberseq[i] = Integer.parseInt(inputtoken[i]);
} catch(NumberFormatException e) {
System.out.println("Parsing error" + " " + e);
System.exit(0);
}
}
}

public void showInput() {
for (int i = 0; i < numberseq.length; i++) {
// System.out.println(numberseq[i]);
}
}

public void getPermutation() {
GenerateOperators gen = new GenerateOperators("+-*/", totaloperator);
List v = gen.getVariations();
System.out.println("Possible Solutions");
for (int i = 0; i < v.size(); i++) {
operatorseq = v.get(i);
manupulate();
}
}

public void manupulate() {

result = 0;

for (int i = 0; i < operatorseq.length(); i++) {
if (i == 0) {
if ((operatorseq.charAt(i)) == '+') {
result = result + (numberseq[i] + numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '-') {
result = result + (numberseq[i] - numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '*') {
result = result + (numberseq[i] * numberseq[i + 1]);
}
if ((operatorseq.charAt(i)) == '/') {
try {
result = result + (numberseq[i] / numberseq[i + 1]);
} catch(Exception e) {
flag = false;
// don't do anything
}
}
} else {
if ((operatorseq.charAt(i)) == '+') {
result = result + numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '-') {
result = result - numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '*') {
result = result * numberseq[i + 1];
}
if ((operatorseq.charAt(i)) == '/') {
try {
result = result / numberseq[i + 1];
} catch(Exception e) {
flag = false;
// don't do anything
}
}
}
}
if (result == resultVal && flag == true) {
totalcounter++;
System.out.println("");
for (int i = 0; i < numberseq.length - 1; i++) {
System.out.print(numberseq[i] + "" + operatorseq.charAt(i));
}
System.out.print(numberseq[numberseq.length - 1]);
System.out.print("= " + result);
}
}

public void count() {
if(totalcounter == 0 ) {
System.out.println("NO EXPRESSION POSSIBLE");
System.exit(0);
}
else {
System.out.println("");
System.out.println("Total Possible Solution :" + totalcounter);
}
}
public static void main(String[] args) {
Main main = new Main();
main.isValid();
main.processInput();
main.showInput();
main.getPermutation();
main.count();
}
}


and one more file which is :

package problemstatement1;

import java.util.List;
import java.util.ArrayList;

public class GenerateOperators {

private String a;
private int n;

public GenerateOperators(String a, int n) {
this.a = a;
this.n = n;
}

public List getVariations() {
int l = a.length();
int permutations = (int) Math.pow(l, n);
char[][] storeCombination = new char[permutations][n];
for (int x = 0; x < n; x++) {
int temp = (int) Math.pow(l, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < l; al++) {
for (int p2 = 0; p2 < temp; p2++) {
storeCombination[p1][x] = a.charAt(al);
p1++;
}
}
}
}

List result = new ArrayList();
for (char[] permutation : storeCombination) {
result.add(new String(permutation));
}
return result;

}

public static void main(String[] args) {
GenerateOperators gen = new GenerateOperators("AAAMMBR", 7);
List v = gen.getVariations();
for (int i=0;i String s1 = v.get(i);
System.out.println(s1);
}

}
}

Feel free to use this code :-).


Wednesday, August 06, 2008

JavaFX Reflection Game !

On the way to exploring little more API of JavaFX, I reached to a fair animation. That is reflection. Here is the output of "crying baby".
Here is the code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.effect.*;

Frame {
title: "Crying Baby"
width: 400
height: 700
closeAction: function() { java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.WHITE
content: [
ImageView {
x: 100
y:10
image: Image {
url: "http://www.powermixradio.com/GGG-SAD-CARTOON.jpg"
}
effect: Reflection {
bottomOpacity:0.1
fraction: 1
topOffset: 50
}
},
ImageView {
x:0
y:300
image: Image {
url: "http://www.toyotapartsstore.com/images/71111_2_%20mirror_8CE1.jpg"
}
opacity:0.5
}
]
}
}


Things to watch:

1. Effect: Reflection -

bottomOpacity:0.1 - set the opacity of image in reflection.

fraction: 1 - set how much part of the image should come in reflection.

topOffset: 50 - How far image from the focus. There are some more useful parameters in this.

2. Opacity of second Imageview allow me to see the reflection of first image, else it will cover the reflection.

On the way to make some moving animation, but I don't know what happened to the support of gif image. gif image works like static image, don't know why ?

Monday, August 04, 2008

Play with Flickr API in Java !

I decided to play with Flickr API's for Java FX coding. But in between I found myself in hell and I started with Java :-). As all of you know Flickr Support hell lot of API to view Image, to search image, to search comment, Image translation, Image upload and many more. Check out here for detailed API. Now using these API's are not at all tough, because its all a game of XML.

Here I have written a small code, which do this :

1. It search one image(it can work for more than one image) from search API of Flickr.
2. It writes the search data on a XML, which I am copying at D:\Hello1.xml.
3. And finally the code is using XML parsing techniques to get the information required for image view.
4. Then I use JDK6 feature of Desktop and open the default browser with the parsed URL. And
Congratulations, you can see the image.

Code, can look little big because of bad coding and writing lot of repetitive things :D.

package flickrapp;

import java.awt.Desktop;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.*;
import java.net.*;
import java.util.*;

public class Main {

public static void main(String args[]) throws Exception {
URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();
DataInputStream dis = new DataInputStream(uc.getInputStream());
FileWriter fw = new FileWriter(new File("D:\\Hello1.xml"));
String nextline;
String[] servers = new String[10];
String[] ids = new String[10];
String[] secrets = new String[10];
while ((nextline = dis.readLine()) != null) {
fw.append(nextline);
}
dis.close();
fw.close();
String filename = "D:\\Hello1.xml";
XMLInputFactory factory = XMLInputFactory.newInstance();
System.out.println("FACTORY: " + factory);

XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename));
int i = -1;
while (r.hasNext()) {

XMLEvent event = r.nextEvent();
if (event.isStartElement()) {
StartElement element = (StartElement) event;
String elementName = element.getName().toString();
if (elementName.equals("photo")) {
i++;
Iterator iterator = element.getAttributes();

while (iterator.hasNext()) {

Attribute attribute = (Attribute) iterator.next();
QName name = attribute.getName();
String value = attribute.getValue();
System.out.println("Attribute name/value: " + name + "/" + value);
if ((name.toString()).equals("server")) {
servers[i] = value;
System.out.println("Server Value" + servers[0]);
}
if ((name.toString()).equals("id")) {
ids[i] = value;
}
if ((name.toString()).equals("secret")) {
secrets[i] = value;
}
}
}
}
}
System.out.println(i);
String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";
try {
URI uri = new URI(flickrurl);
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

if (desktop != null) {
desktop.browse(uri);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
}

Now see this line :

URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();

Here some important thing to see :

http://api.flickr.com/services/rest/?method=flickr.photos.search -> this is the way to write Flickr API.

api_key=e3471e67d4ac10c64055420d9b211b4f -> required for service. This is my api_key, you can have your own. Just go to flickr service and generate your API_key

per_page=1 -> Here is what I meant one image, if you can change this to 10. It will gather information of top 10 images in XML file.

text=Bangalore -> Sorry, I have hard coded it for now. This is the search string.

Now, look at the XML file get generated in D:\Hello1.xml. You can see one entry with tag photo inside photos. So, we need to take some data from this XML file and add in proper style to get the correct URL and that is here:

String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";

Again, lot of things are hard coded(which I will correct in next post). Since only one image (i=0). I am assuming its a jpg image :D. Now calling Desktop API, you can load this image on default browser.

Now, this is still a live question, for certain keyword search, it gives the same result like when I search for keyword "Vaibhav", code and search box of Flickr provided the same result(which is not my photo :-( ) whereas if I search on things like "Bangalore", result is not similar for many cases. I don't know how Flickr handles it internally.

Probably next I will try to upload image or translate image but in Java FX :-)

Wednesday, July 30, 2008

Navigation Code in JavaFX

So finally I am able to write a small code with the new Java FX API and Builder provided in NB 6.1. I have also seen one bug got fixed (maybe initially it was handled on a different way). Initially when we make any FX project in Netbeans, it basically store the *.fx code into classes folder as well. There is no way one can find the .class file of the .fx file, which is not a problem now.

I have written one small navigation code of map from key control. Which moves the map left, right, up and down from the corresponding key. And the most part of the code line is to handle the boundary condition like the image should not move left when it is already in left most region and so on. Thanks to Vikram for helping me out in writing boundary condition, this is always confusing for me :-D. Here is the small code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.paint.Color;
import javafx.input.KeyEvent;
import javafx.input.KeyCode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.input.MouseEvent;
import javafx.scene.transform.Translate;
import java.lang.*;
import javafx.scene.geometry.Line;

var x1 : Number = 0;
var y1 : Number = 0;
//var myImage = Image { url: "{__DIR__}/./earth-map-big.jpg" };
var myImage = Image { url: "http://arstechnica.com/reviews/4q00/macosx-pb1/images/earth-map-big.jpg" };
var line: Line;

Frame {
title: "MyApplication"
width: 500
height: 500
resizable: false

closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true
stage: Stage {
fill:Color.BLACK
content: [
ImageView {
image : myImage
transform : [
Translate { x : bind x1, y : bind y1 }
]
onKeyPressed: function( e: KeyEvent ):Void {
System.out.println(x1 + " " + y1);
if(
e.getKeyText() == "Left")
{
if(x1 < 0) {
System.out.println(x1);
x1+=50;
}
}
if(
e.getKeyText() == "Right")
{
if(Math.abs(x1 - 500) < myImage.width) {
System.out.println(x1);
x1-=50;
}
}
if(
e.getKeyText() == "Down")
{
if(Math.abs(y1 - 500) < myImage.height) {
System.out.println(y1);
y1-=50;
}
}
if(e.getKeyText() == "Up")
{
if(y1 < 0) {
System.out.println(y1);
y1+=50;
}
}
}
opacity:1
}
]
}
}

I am loading the image from URL itself, so it will take sometime(because Image size is 3200 X 1600). Rest all is mathematics :-). Still lot more fancy job to do !

Original Post




Type Checking - Java, Fast !

Lots of our friends keep on asking, why to use Java SE 5.0 or Java SE 6. And most of the time you need to reply something impressive, then only they will start using it and can understand more benefits. I was reading the gradual performance improvement in JDK versions which is quite interesting. Java has spotted all its reason to being slow (very nice article, which speaks why Java is slow than C++) and optimized those on max level. One of the reasons mentioned in this article was Lots of Casts. And that's true, a good, big project code goes about millions of cast checking in Java and off course need attention for optimization. JDK 5 and onwards has done a fast subtype checking in Hotspot VM. This blog is dedicated on a small talk on the same, for detail read this article written by John and Cliff.

Prior to 5, Every Subtype has cached with its SuperType(casting of which is correct). The cache strength is 2 and if results return negative then its goes for a VM call which resolves this problem and caches if VM resolves it as positive. So anytime unavailability in cache is a costly operation where we need to make a call for VM. And in the worst scenario mentioned in SpecJBB we can have 3 rotating elements with 2 cache.

So, [A B] in cache <---- C found by VM and get cached, A is out now.

[B,C] in cache <-------- A negative test, VM call(+), get cached, B out.

[C,A] in cache <-------- B negative test, VM call(+), get cached, C out !

So, in basic term we can't trust on complexity(calls happen at runtime). And hence it better to move on a better algorithm. The new algorithm pass the code through an optimizer which checks more specification at compile time. Like if Base class and Derived class is known at compile time only. It try to understand lot of code at compile time only. It put the entire code inline and there is no requirement of VM calls. Complexity is quite consistent and it takes one load for most of the object or object array.

This also divide the subtype checks into primary and secondary checks. For Class, Array of Classes and for array of primitive value, primary check has been done whereas interface and array of interface are handled by secondary check. Finally a smart algorithm combines them.

In primary subtype check:

Aim to Check: Is S a subtype of T ? Calculate the depth of S and T. Depth mean to say all the parent. Though it is done in some base level or assemble level, I am writing a code in Java to find out the depth. Here is the code using reflection API's:

package findparent;
public class Main {

public static void main(String[] args) throws Exception {
String[] display = new String[10];
int i = 1;
FifthClass tc = new FifthClass();
Class classname = tc.getClass();
display[0] = classname.getName();
Class parent = classname.getSuperclass();
while (!(parent.getName().equals("java.lang.Object"))) {
display[i] = parent.getName();
classname = parent.newInstance().getClass();
parent = classname.getSuperclass();
i++;
}
display[i] = "java.lang.Object";
for (int j = 0; j <= i; j++) {
System.out.println(display[j]);
}
System.out.println("Depth of tc is " + i);
}
}

class FirstClass {
}

class SecondClass extends FirstClass {
}

class ThridClass extends SecondClass {
}

class ForthClass extends ThridClass {
}

class FifthClass extends ForthClass {
}


Now the algo. says:

S.is_subtype_of(T) :=
return (T.depth <= S.depth) ? (T==S.display[T.depth]) : false;

And further a lot of optimization. Which we will check in next blog :-). I will also try to cover how the secondary Subtype check is being done and also how to combine both the checks.

Till now, make a big inheritance tree and try to see the difference between older JDK and JDK5 onwards.

Small Java FX example

OK, nothing to laugh. I know my animation sense is little poor. But here I tried to move a ship, in the way they show in movies -D. Nothing like that, I have tried to give a sinusoidal movement of a ship. In the comment section, you can see there is a sea image as well. Animation was looking little ugly with sea, so I removed it :-). But point to note, you can give any animation to a image based on any mathematical methods. And if you have a complex equation, you can fit that in, in place of my simple sin curve. Here is the code:

package move;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.paint.Color;
import java.lang.Math;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;

var time : Number = 0.0;


var timeline : Timeline = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames :
KeyFrame {
time : 5ms
action: function() {
time += 0.02;
}
}
};
Frame {
title: "MyApplication"
width: 1200
height: 500
closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.AQUA
content: [
/* ImageView {
image: Image {
url: "http://birdblog.merseyblogs.co.uk/sea21206.jpg"
}
},
*/
ImageView {
x:bind(100 + time * 10)
y:bind(100 + Math.cos(time) * 10)
image: Image {
url: "http://lal.cas.psu.edu/Research/visualiz/images/boat.gif"
}
}
]

}
}
timeline.start();


Just 3-4 drags from Netbeans 6.1 FX viewer :

1. One Timeline and an action inside it.

2. One Frame.

3. One Image.

Thats it ! Set the code logic and rest leave all the work on binding :-). Quite simple, just that I am not able to make some good animation out of it !

Originally posted on http://blogs.sun.com/vaibhav

Tuesday, July 15, 2008

JDK6 comparing with JDK1.4.2

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:

import java.util.*;

public class RuntimePerformanceGC {

public static void main(String[] args) {
RuntimePerformanceGC ob = new RuntimePerformanceGC();
Vector v = new Vector();
java.util.Date now = new java.util.Date();
long t1 = now.getTime();
ob.addItems(v);
java.util.Date now1 = new java.util.Date();
System.out.println(now1.getTime()-t1);
}
public void addItems(Vector v) {
for(int i =0;i<500000;i++)
v.add("Item" + i);
}
}

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again.

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)

JavaFX + Java

Tough to understand the code conversion :). I have seen the Java code of corresponding JavaFX code. Though its tough to map but we can see the correct correspondence. Let see this :

import javafx.ui.*;

Frame {
title: "Hello World JavaFX"
width: 200
content: Label {
text: "Hello World"
}
visible: true
}

and the corresponding Java Code:

import com.sun.javafx.runtime.Entry;
import com.sun.javafx.runtime.FXObject;
import com.sun.javafx.runtime.InitHelper;
import com.sun.javafx.runtime.Public;
import com.sun.javafx.runtime.Static;
import com.sun.javafx.runtime.location.AbstractVariable;
import com.sun.javafx.runtime.location.BooleanVariable;
import com.sun.javafx.runtime.location.DoubleVariable;
import com.sun.javafx.runtime.location.ObjectVariable;
import com.sun.javafx.runtime.sequence.Sequence;
import javafx.ui.Frame;
import javafx.ui.Frame.Intf;
import javafx.ui.Label;
import javafx.ui.Label.Intf;

public class Hello
implements Hello.Intf, FXObject
{
@Public
@Static
public static Object javafx$run$(Sequence paramSequence)
{
Frame localFrame = new Frame(true);
localFrame.get$title().setFromLiteral("Hello World JavaFX");
localFrame.get$width().setAsDoubleFromLiteral(200.0D);
Label localLabel = new Label(true);
localLabel.get$text().setFromLiteral("Hello World");

localLabel.initialize$(); localFrame.get$content().setFromLiteral(localLabel);

localFrame.get$visible().setAsBooleanFromLiteral(true);

localFrame.initialize$(); return localFrame; }
public void initialize$() { addTriggers$(this); userInit$(this); postInit$(this); InitHelper.finish(new AbstractVariable[0]); }
public static void addTriggers$(Hello.Intf paramIntf) { }
public Hello() { this(false); initialize$(); }
public static void userInit$(Hello.Intf paramIntf) { }
public static void postInit$(Hello.Intf paramIntf) { }
public static void main(String[] paramArrayOfString)
throws Throwable { Entry.start(Hello.class, paramArrayOfString);
}
}

This I have done by generating the class file and then de-compiled the class file.

Frame of JavaFX - Frame localFrame = new Frame(true);
title and text of JavaFX
- localFrame.get$title().setFromLiteral(”Hello World JavaFX”);
- localLabel.get$text().setFromLiteral(”Hello World”);

Visibility of JavaFX - localFrame.get$visible().setAsBooleanFromLiteral(true);

Lot of code is written to support JavaFX environment, which is completely justifiable. Don’t able to get why methods are written with $. If any clue, please let us know also.

Saturday, June 28, 2008

Performance Improvement in JDK6

Original Post: http://blogs.sun.com/vaibhav/entry/why_jdk6_again

Content:

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:



import java.util.*;
public class RuntimePerformanceGC {
public static void main(String[] args) {
RuntimePerformanceGC ob = new RuntimePerformanceGC();
Vector v = new Vector();
java.util.Date now = new java.util.Date();
long t1 = now.getTime();
ob.addItems(v);
java.util.Date now1 = new java.util.Date();
System.out.println(now1.getTime()-t1);
}
public void addItems(Vector v) {
for(int i =0;i<500000;i++)
v.add("Item" + i);
}
}

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again.

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)

Java 6u10 Features

Sorry for not writing for a long time. Actually I have start writing more on Sun Blog Site, so this blog space get affected . But today I got time to archive some of my blog work on this site.
Here is the latest :

Current work: Presentation in BOJUG meet. Download here. Don't forgot to give your comments :-). There are some demos which I try to cover in blog.

These slides basically talks about Java SE 6u10 features. Some of them are cool like

-> Next Generation Plugin where you can drap plugin outside the browser.

-> Kernel JRE. Download small JRE.

-> Nimbus Look And Feel

-> New Applet feature

Saturday, June 21, 2008

Disk Space Check

Take care of disk space when you are writing a big program :). Use JDK 6 features:

import java.io.File;

public class DiskSpaceCheck {
public DiskSpaceCheck() {
File file = new File("E:");
System.out.println("E:");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("E://movie");
System.out.println("E://movie");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("/");
System.out.println("n/");
System.out.println("Total: " + file.getTotalSpace());
System.out.println("Free: " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
}

public static void main(String[] args) {
new DiskSpaceCheck();
}
}

I was actually very suprised that why this feature came so late.

Friday, May 16, 2008

Taking input into batch file(sh file) from Java code

Most of the time when we start server, we write lot of code to optimize the condition. Most of those things are tough to write in Java but easy for batch file or sh file to work on. Like, go into a folder, set JAVA_HOME, setting some heap size and then fire the server. Things are not always start forward, sometime we need to pass some message or some path or some value from Java code to batch file.

Here I tried to write one. Say my JAVA_HOME is dynamic and on some condition I decide what's going to be JAVA_HOME and further on that what java and javac going to run(means setting path).

import java.io.*;
public class batchCheck {
public static void main(String[] args) {
//All JavaHomes
String javaHome[] = {"E:\\Program Files\\Java\\j2sdk1.4.2_05", "E:\\Program Files\\Java\\jdk1.6.0"};
String path;
String line = "";
String pathFile = "E:\\Program Files\\Java\\jdk1.6.0\\bin\\JavaOutput";
String whichJDK = "";
String decisionMaker = "142";
if (decisionMaker.equals("142")) {
whichJDK = javaHome[0];
} else {
whichJDK = javaHome[1];
}
try {
path = whichJDK + "\\bin";
String cmds[] = {"check.bat", pathFile, whichJDK, path};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Now, you can see my check.bat file:

cd %1
DEL HelloWorld.class
set PATH=%3
set JAVA_HOME=%2
echo %JAVA_HOME%
javac HelloWorld.java
java HelloWorld
exit

So, see how we can access the values from java file into batch file from %1, %2, %3 ... ($1,$2... in sh). Simply I moved on to the path where HelloWorld.java resides. I have deleted the old class file and the set the path, set the JAVA_HOME, compiled with javac of new JAVA_HOME and ran the code + exit :D.

Lot many things have been done from a very simple code.

Monday, May 12, 2008

Nimbus Look And Feel !

Good news for all the user, using JDK6. Though I am little late in writing blog on this but its OK ;). JDK6 current update comes with a new L&F(Look And Feel) called Nimbus.

Nimbus provide more lively look and feel in Swing UI. Here are some examples:

Default Look And Feel(Click to see enlarged mode)
Nimbus Look And Feel((Click to see enlarged mode)

Since the image is little small and related to my Online Java Project(which I can't change), so I provide another example here from my last blog code.

Default Look And Feel
Nimbus Look And Feel
Something more interesting is focus traversal on components. For Default L&F, you can see that there is a dotted rectangle on Button 3, which says "Focus is here" whereas in Nimbus you can see Button 1 with little bluish highlight which says "Look at my focus" :)

Quickest way to try, command line:

Run my previous (or any UI code) with the following option:

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

Off course, you can do it with code :
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
Use try, catch and respect Exception handling as well.