>

Vaibhav's Blog Space

Java - Instruction set rather than time

Monday Sep 22, 2008

One guy asked a question on a Java Forum: which operation is faster - post-increment or pre-increment. I really don't feel these things make a big difference in code performance. I have written a small code to check what nanosecond API of Java is telling about it. And again I reached to a wrong benchmarking. 

class InstructionCheck {
    private int x = 0;
 
    public void countup_() {
        ++x;
    }
    public void countup() {
        x++;
    }
    public void countdown() {
        x--;
    }
    public void count2up() {
        x = x+2;
    }
    public void count2down() {
        x = x-2;
    }
    public static void main(String[] args) {
        long stime = 0;
        long etime = 0;
        InstructionCheck ic = new InstructionCheck();

        stime = System.nanoTime();
        ic.countup_();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countup();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countdown();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2up();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2down();        
        System.out.println(System.nanoTime() - stime);
    }
}         

And the output after several run: 

20952
5308
5587
5587
5308

Now, no doubt the first value is not correct, because of some other reason(I really don't know why) but may be some reigster setting, first time using the class or something else.

But if we see the assemble code, it will simple say that there is(should) no difference in ++i or i++. Look at this :

public void countup_();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

public void countup();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

The complete assemble code, you can see by option javap -c FileName. My personal opinion is to check the instruction set rather checking the time by nanosecond or millisecond because some benchmarking issue can lead to a different result(which can be completely wrong, like in our case). Here we can easily see that ++i and i++ leads to same instruction and hence both will be more or less equal in performace.

[8] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

A nasty Problem - Java Code

Monday Sep 15, 2008

Few days back, I got a problem in which actually I have to get the fields, constructor and method name from a java class. One can think of using reflection API and the problem is easy to solve, but that is not the case. Reflection API can only be used on class files not Java file. Than a quick idea came into mind to compile the file internally, use reflection and then delete the class file, if user don't want to see it. This is never be a tough job if I use JDK6 JavaCompiler code which is :

import java.io.IOException;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JDK6FirstCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "HelloWorld.java");
    System.out.println("Success: " + (results == 0));
  }
}


class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}


But but, I was constraint to use JDK5 or less. So, this JDK6 API is not worth for me :-(. Finally, came up with a small code, which probably can do this in all the case. Hoping it will not lose any generic behavior and run in all cases.

Here is the code:

import java.io.*;

public class CompileCheck {

public void compileClasses2() {
        try {
            String command = System.getProperty("java.home")+File.separator + ".." + File.separator+"bin"+File.separator+"javac " + "HelloWorld.java";
            System.out.println(command);
            Runtime.getRuntime().exec(command);
    } catch (Exception e) { }
    }


    public static void main(String[] args) {
 
        CompileCheck c = new CompileCheck();
        c.compileClasses2();
    }
}


In place of HelloWorld, I can surely use any path where the java file resides. And off course, I can use *.java as well :-). Please let me know your opinion or any other method easier than this from which I can get class methods, attributes and all from a java file.

[3] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Last week.. a competition code !

Saturday Sep 13, 2008

Last week, IEC 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<String> 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<String> 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<String> result = new ArrayList<String>();
       for (char[] permutation : storeCombination) {
           result.add(new String(permutation));
       }
       return result;

   }

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

   }
}

Feel free to use this code :-).



[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Sunday work - Tracing in FX and Blog Change :-)

Sunday Sep 07, 2008

 I did some fine tuning in my blog page after long time :-). I have added two more link in Links section, which can be helpful in :

1. Telling which JRE's are there on your machine(blog readers) machine.

2. And second will install the latest JRE(It will start installation directly, so careful :-D)

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 :

Here the ball is moving in a cosine fashion and so the trace. Easiest way to achieve this is to write code in update method. Have a look on the code, its small:

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 !

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Guassian Blur Example JavaFX

Saturday Sep 06, 2008

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.

Here is the simple code :

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},
 
                ]
            },
 
       ]
    }
}

[3] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

BOJUG meet - 30th Aug.

Sunday Aug 31, 2008

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.


[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Next BOJUG meet

Thursday Aug 28, 2008

We are welcoming all the Java Engineers in Bangalore to join BOJUG. Its Bangalore Open Java Users Group. Before going into the schedule of this time meet, we motivate you to join the BOJUG group at: http://bojug.wikispaces.com/ and http://bojug.dev.java.net. Now, here are the talks of the week: 

The next Bangalore Open Java Users Group (BOJUG) (http://bojug.dev.java.net)  meet has been planned for Saturday August 30, 2008,Time: 11.30 AM .

Venue:

Thoughtworks Bangalore

Tower C, Corporate Block, Diamond District, Airport Road
Landmarks: The first set of buildings after the Indiranagar flyover,
opp to the TJIF restaurant.

Google Maps Location: http://maps.google.com/maps?f=q&hl=en&geocode=&q=thoughtworks,+bangalore&ie=UTF8&filter=0&ll=12.996864,77.651196&spn=0.075603,0.154495&z=13

Time: 11.30 AM
Session Details:

1. Java FX..Its just the beginning-Vaibhav Choudhary

JavaFX Preview SDK
NetBeans Compatibilty
Demo, Demo, Demo, Demo .. and only Demo. How to make timeline, reflection, constraint,easing, shapes, animation, Java AWT/Swing.
Last we will try to see how to use it in applet or any type of web code.

2. Beans Binding and Beans Validation- Sathish Kumar

Short discussion on the above topics

3. Tomcat Internals - Sriram Narayanan

In this talk, Sriram will cover in brief various Tomcat configuration issues (server.xml, how to avoid having to deploy during development
time, etc). He'll next cover interesting topics such as developing custom Tomcat components, and how the component assembly mechanism
works.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Button Tabs with effects in JavaFX !

Tuesday Aug 19, 2008

It looks good, so I decided to put before the completion of work. I was trying to simulate some fancy effects on button, so that I can embed it somewhere in some site. Here what is the class for Button:

public class Button extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute text: Text;
    public attribute rectangle: Rectangle;
    public attribute content: String;
 
    public function create(): Node {

Now, the buttons will look like: 

 If you move the focus on any of the button, it will shine like this :

 or like this :

This simple 2 line animation is achieved by playing with the opacity code. Though I am not able to fit my text inside the button which currently I am trying to bind out. But simple flashy buttons are easy to achieve. Here is the code:

package flashybutton;

import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.text.*;
import javafx.scene.geometry.*;
import javafx.scene.paint.Color;
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.ext.swing.TextField;
import javafx.scene.Font;
import javafx.scene.FontStyle;
import javafx.scene.paint.*;
import javafx.input.MouseEvent;


var x: Number = 100;
var y: Number = 100;
var color: Color;
var buttons:Button[]; 
var text: Text;
var content: String;
var width: Number = 100;
var height: Number = 40;
var arcWidth:Number = 10;
var arcHeight: Number = 10;
var opacity: Number = 0.6;

for( i in [1..5] ) {
    insert Button {
        x:100 + 100 * i,
        y:100,
        content: "HelloWorld" + i,
        opacity: 0.6
    } into buttons;
}     
Frame {
    title: "MyApplication"
    width: 1000
    height: 200
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.BLACK
        content: [ 
            buttons
        ]
    }
}

public class Button extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute text: Text;
    public attribute rectangle: Rectangle;
    public attribute content: String;
 
    public function create(): Node {
        return Group {
            content: [
                Rectangle {    
                    x : bind x,
                    y : bind y, 
                    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: 0.0 color: Color.BLACK },
                            Stop { offset: 0.5 color: Color.GOLD },
                            Stop { offset: 1.0 color: Color.BLACK }
                        ]
                    },
                    width: 100
                    height: 40
                    arcWidth: 10
                    arcHeight: 10
                    opacity: bind opacity
                    onMouseMoved: function( e: MouseEvent ):Void {
                        opacity = 1.0;
                    }
                    onMouseExited: function( e: MouseEvent ):Void {
                        opacity = 0.6;
                    }
                },
                Text {
                    x: bind x + 10,
                    y: bind y + height / 2 + arcHeight / 2;
                    content: bind content
 
 
                }
            ]
        }
    }
}

[4] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Motion of Ball Under Gravity - JavaFX

Monday Aug 18, 2008

As written in the last blog, now we can use those MotionBall into giving some kind of motion. Here I have tried to give a simple motion of ball under gravity. After every hit there is an energy dissipation and the ball will slow down at end. The colors of balls, initial positions and radius are all random but under a constraint. 

Now, the motion of the balls should get called in timeline. Like this:

 var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 16ms
            action: function():Void {
                for(ball in balls) {
                    ball.motion();
                }
            }
        }
    ]
}

Here is the final code. I tried to write the value as generic as possible but pardon me if there is some hardcoded value written somewhere :

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

// Java Legacy
import java.lang.Math;
import java.util.Random;
import java.lang.System;


var balls:GravityBall[];
var gravity:Number= 0.1;
var width:Number = 1200;
var height:Number= 500;
var dampFactor: Number = 0.9;
 
var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 16ms
            action: function():Void {
                for(ball in balls) {
                    ball.motion();
                }
            }
        }
    ]
}

var rnd : Random = new Random();

for( i in [1..5] ) {
    insert GravityBall {
        x : rnd.nextInt( 100 ), y :  rnd.nextInt( 300 ), radius : rnd.nextInt( 10 ) + 20
        color : Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))
        , opacity : 0.9
    } into balls;
}    


var rect = Rectangle {
    x: 0, y: 500
    width: 1200, height: 10
    fill: LinearGradient {
        startX: 0.0
        startY: 0.0
        endX: 1.0
        endY: 0.0
        proportional: true
        stops: [
            Stop { offset: 0.0 color: Color.TRANSPARENT },
            Stop { offset: 1.0 color: Color.WHITESMOKE }
        ]

    }
}
Frame
{
 
    title: "MyApplication"
    width: 1200
    height: 732
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill : Color.BLACK
        content: [
            balls,
            rect
        ]
    }
}

timeline.start();

public class GravityBall extends CustomNode {

    public attribute x : Number;
    public attribute y : Number;
    public attribute radius : Number;
    public attribute color : Color;
    public attribute velocity : Number;
 
    public function motion(): Void {
        velocity += gravity;
        x += 1;
        y += velocity;
 
        if(x + radius > width ) {
            x = width - radius; //for ending at the boundary
        }
        if( y + radius > height ) {
            y = height - radius;
            velocity *= -dampFactor;
        }
    }
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill: bind color
 
        };
 
    }
} 

This is small output view :


[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Insertion trigger in JavaFX

Saturday Aug 16, 2008

This weekend I have written some physics equation in JavaFX like motion under gravity and collision motion. In all  complex code, we have to write a class of MotionBall, which consist attribute like X position, Y position, Velocity, Mass and Color of Ball like:

public class MotionBall extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute velocityX: Number;
    public attribute velocityY: Number;
    public attribute mass: Number;
    public attribute radius: Number;
    public attribute color: Color;
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill : bind color
 
        };
    }
} 

After this, the important part is to fill these data outside the class. Say, I want to make 5 instance of MotionBall. And I want to give Center X, Center Y, radius and color. Here in this code, I want to put the Balls at the random position with random radius with random color :-). Here goes the insertion trigger in JavaFX:

package insertion;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import java.util.Random;


var radius: Number;
var balls: MotionBall[];

var rnd : Random = new Random();

 for( i in [1..5] ) {
                insert MotionBall {
                    x : rnd.nextInt( 170), y :  rnd.nextInt( 170 ), radius : rnd.nextInt( 10 ) + 20
                    color : Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))
                    , opacity : 0.9
                    } into balls;
                }    
Frame {
    title: "Insertion Example"
    width: 250
    height: 250
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.BLACK
        content: 
            bind balls
 
    }
}
 
public class MotionBall extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute velocityX: Number;
    public attribute velocityY: Number;
    public attribute mass: Number;
    public attribute radius: Number;
    public attribute color: Color;
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill : bind color
 
        };
    }
}

This is how output looks like : jar file.

I have written some attribute for further use, so please ignore the use.


[3] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Need more than Preview Mode - JavaFX

Monday Aug 11, 2008

JavaFX Preview SDK came up somewhere in the middle of last month. It is no doubt one of the important thing required. But still the preview is not enough to remove the tiny complexity. I don't do lot of JavaFX coding, but whatever I do, most of the time I spend in putting the circle at right place, adjusting the rectangle corners, making the polygon of the correct shape, where to put the image and many more. Because the preview generates a code which need a lot of modification(why not builder makes it for me). 

Here how it works :

When I drag the line on my code part, it will write something like :

Line {
                startX: 10, startY: 10
                endX: 230, endY: 100
                strokeWidth: 1
                stroke: Color.BLACK
        }

Which is my partial requirement. I want my line to go in the position where it is required in the output window, not a default one. Would love to see Screen View or Output View or Image View where I can draw the objects like Circle, Line, Polygon, Image and drop at a point where it is required in the Output Window. I mean, simply how it happens in Flash or happens in Paint. When I drag say Circle, it comes into editable mode, I can do operation on it, I can increase its radius, I can change the center, I can fill the color and many more and finally settle down at the right position.

If I am not wrong, then we all invest(waste) 20-30 percent of the time still in putting stuff at right position. Talking about the complex drawing, say like making a face, it will take more than 40 percent of time. Why not we can have a View which do that for us. It is just my personal opinion, for rest JavaFX preview is simple and sober. I am damn sure, FX Engineers are working on this. Say if all this is done, poor developer like me can put more brain on writing logic code like Mouse Movement, Key Events, Binding calls(even binding should be done by Builder) and more.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

JavaFX, Constrain check - Next Part !

Sunday Aug 10, 2008

As we discussed in the last blog, about easing and constraint. Now we have seen the ball is moving inside the box but not completely. And this is not possible as well because the mouseMove code has been written on the box and mouse can move anywhere in the box. So, the basic funda comes first is to make one virtual box bigger than target box and the mouseMove code should be written on the outer virtual box rather than the box inside which we want to move our ball. Now the real constraint part, that will be written inside the onMouseMove code: 

                onMouseMoved: function( e: MouseEvent ):Void {
                    mouseX = e.getX();
                    mouseY = e.getY();
                    if(mouseX < rect.x + circleRadius ) {
                        mouseX = rect.x + circleRadius
                    };
                    if(mouseX > rect.x + rect.width - circleRadius ) {
                        mouseX = rect.x + rect.width - circleRadius
                    };

                    if(mouseY < rect.y + circleRadius ) {
                        mouseY = rect.y + circleRadius
                    };
                    if( mouseY > rect.y + rect.height - circleRadius ) {
                        mouseY = rect.y + rect.height - circleRadius
                    };
                }

Here, rect is the target box inside which we want the ball to move. So, if mouse position is going out of the boundary, we are pushing it inside the boundary. I am still damn sure, some checking may be missing. Now, this mouseMove will go into the outer bigger circle. Here is the final code: 

 package constraintcheck;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import javafx.input.MouseEvent;
import javafx.scene.transform.Translate;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import java.lang.Math;
import javafx.scene.geometry.Rectangle;

var mouseX : Number = 100;
var mouseY : Number = 100;
var circleX : Number = 300;
var circleY : Number = 300;
var t : Number = 100;
var easing : Number = 0.05;
var circleRadius : Number = 50;

var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 16ms
            action : function() {
                if( 
                Math.abs(mouseX - circleX ) > 0.1 ) {
                    circleX = circleX + (mouseX - circleX ) * easing;
                }
                if( Math.abs(mouseY - circleY ) > 0.1 ) {
                    circleY = circleY + ( mouseY - circleY ) * easing;
                }
            }
        }
    ]
}

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

    var rect = Rectangle {
        x: 100, y: 100
        width: 400, height: 400
        fill: Color.RED
   }
    stage: Stage {
        content: [ 
            Rectangle {
                x: 0, y: 0
                width: 500, height: 500
                fill: Color.BLACK
                onMouseMoved: function( e: MouseEvent ):Void {
                    mouseX = e.getX(); 
                    mouseY = e.getY();
                    if(mouseX < rect.x + circleRadius ) { 
                        mouseX = rect.x + circleRadius
                    };
                    if(mouseX > rect.x + rect.width - circleRadius ) { 
                        mouseX = rect.x + rect.width - circleRadius
                    };
 
                    if(mouseY < rect.y + circleRadius ) { 
                        mouseY = rect.y + circleRadius
                    };
                    if( mouseY > rect.y + rect.height - circleRadius ) { 
                        mouseY = rect.y + rect.height - circleRadius
                    };
              &