X

Vaibhav's Blog Space

Recent Posts

Java

Feb 2017 - JUG and Basics of Java ClassLoader

Today in Bangalore JUG, we had a small presentation on Java Classloaders. Here is the presentation on "Working with Java Class Loading"On 25th Feb, 2017, we have witnessed the presentation on following :-Talk 1:Name: Vaibhav Choudhary Company : Oracle Topic : Diving deep into Java Class loadersAgenda :1. Basics of Java class loader 2. General issues that are related to class loader like NoClassDefFoundError, ClassCastException ... 3. Parallel Class loading 4. How class loader impacts your application. 5. Changes in class loader in JDK9. 6. Random codes here and there.Talk 2:Name: SaifiTopic: Module System in Java 9Modularity is the approach to manage and reduce the complexity associated with structuring of large code bases. 'module' is not just a new 'keyword' in Java 9, but has deep impact on the platform. This means there are changes to the languages, virtual machine and the standard libraries.In the session, i will be discussing about. CLASSPATH hell . modular JDK / JigSaw project . module descriptor . how to structure your code base around modules . keywords like module, exports, provides, uses, with, to, and requires . how to write your first module . linking modules . overview of platform modules . tooling available jmod, jlink . overview of JSR 376 . overview of JEP 261 . highlight of some interesting discussion on jpms-spec mailing list . code and demoTalk3 Name: Kunal Grover Topic : Failure resilient microservices model with Java8 Agenda : It will be a short talk explaining the model and I would briefly touch upon how it can be implemented using Java81. Circuit breaker mechanism with microservices 2. Java8 CompletableFuture introduction, timeout and retries 3. Monitoring ideas

Today in Bangalore JUG, we had a small presentation on Java Classloaders. Here is the presentation on "Working with Java Class Loading" On 25th Feb, 2017, we have witnessed the presentation...

Java

A fast overview of Just-In-Time(JIT) Compiler

JIT comes in these flavors: C1 (Client compiler) -client option C2 (Server compiler)-server option -XX:+TieredCompilation - Better decision of compilers. Common Optimizations done by Just-In-Time (JIT) Compiler do:  1. Eliminate dead codes and Expression optimization. int someCalculation(int x1, int x2, int x3) {  int res1 = x1+x2; int res2 = x1-x2;  int res3 = x1+x3; return (res1+res2)/2; }will be converted toint someCalculation(int x1, int x2, int x3) {return x1; }  2. Inline Method- Substitute body of the method (<35 bytes of JVM bytecode)- This provides the best optimization by JIT- A better inline that C++ For Example: int compute(int var) {int result;if(var > 5) { result = computeFurther(var); }else { result = 100;}return result;} If you call myVal = compute(3); it will get converted into myVal = 100;3. Caching Technique:Point findMid(Point p1, Point p2) {Point p;p.x = (p1.x + p2.x)/2;p.y = (p1.y + p2.y)/2;return p; p1.x, p2.x -> It can convert into temp1, temp2 and can be cached.4. Monomorphic dispatch:public class Birds {private String color;public String getColor() {return color;} }myColor = birds.getColor(); If there is no other override of this method, it will convert into public class Birds {String color;}mycolor = birds.color; 5. Null Checks Removal:x = point.x;y = point.y;At JVM it is equivalents to:if(point==null) throw new NullPointerException();else {x = point.x;y = point.y;}  But if the code will not throw NullPointer for more than threshold reference, it will remove the if check.6. Threading Optimizations: - Eliminate locks if monitor is not reachable from other threads- Join adjacent synchronized blocks on the same object7. Loop Optimizations: - Combining loops – Two loops can be combined if taking equivalent time.- Inversion loops – Change while into do-while. (why, just give a javap -c)- Tiling loops – Re-organize loop so that it will fix in cache. VM Args:Xint – Interpreter modeXcomp – Compiled modeXmixed – Interpreter + Compiler-server → C2 compiler-client → C1 compiler-XX:+TieredCompilation → C1 + C2 (used by 32/64 bit mode) Logging Options:-XX:+UnlockDiagnosticVMOptions-XX:+LogCompilation-XX:LogFile=<path to file>-XX:MaxInlineSize=<size>-XX:FreqInlineSize=<size> (For more see my last blog)

JIT comes in these flavors: C1 (Client compiler) -client option C2 (Server compiler)-server option -XX:+TieredCompilation - Better decision of compilers. Common Optimizations done by Just-In-Time (JIT)...

Java

VM Options for C1 and C2

Many Java Developers often ask what are the flag options available for C1 and C2 Compilers or what are the flag options available for JIT compilers. Though most of the time our slides will cover some of the important VM options (-XX) but certainly we can't  provide the list of complete option in slides. This is actually quite a trivial job. Here it goes: 1. Complete VM global flag option (redirecting it to out file): java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal > out wc -l < out 764  // Total available options, did on jdk7 2. If you will check without  UnlockDiagnosticVMOptions, the no.s will be bit less. java  -XX:+PrintFlagsFinal > out wc -l < out 672  2. This document comes with the beautiful option of where it is been used like Product, C2 diagnostic, C1 Product and many more. So, just grep the out file with "C2" and see what options are available for you on C2 Compiler and which options are product options and which are diagnostic or logging options.  cat out | grep "C2"  A list will come something like:      intx AliasLevel                                = 3               {C2 product}      bool AlignVector                               = true            {C2 product}      intx AutoBoxCacheMax                           = 128             {C2 product}      bool BlockLayoutByFrequency                    = true            {C2 product}      intx BlockLayoutMinDiamondPercentage           = 20              {C2 product}      bool BlockLayoutRotateLoops                    = true            {C2 product}      bool BranchOnRegister                          = false           {C2 product}      intx ConditionalMoveLimit                      = 3               {C2 pd product}      bool DebugInlinedCalls                         = true            {C2 diagnostic} ccstrlist DisableIntrinsic                          =                 {C2 diagnostic}      bool DoEscapeAnalysis                          = true            {C2 product}      intx DominatorSearchLimit                      = 1000            {C2 diagnostic}      intx EliminateAllocationArraySizeLimit         = 64              {C2 product}      bool EliminateAllocations                      = true            {C2 product}      bool EliminateAutoBox                          = false           {C2 diagnostic}      bool EliminateLocks                            = true            {C2 product}      bool EliminateNestedLocks                      = true            {C2 product}      bool IncrementalInline                         = true            {C2 product}      bool InsertMemBarAfterArraycopy                = true            {C2 product}      intx InteriorEntryAlignment                    = 16              {C2 pd product}      intx LiveNodeCountInliningCutoff               = 20000           {C2 product}  3. Running the same option for C1. cat out | grep "C1"  We can see:      bool C1OptimizeVirtualCallProfiling            = true            {C1 product}      bool C1ProfileBranches                         = true            {C1 product}      bool C1ProfileCalls                            = true            {C1 product}      bool C1ProfileCheckcasts                       = true            {C1 product}      bool C1ProfileInlinedCalls                     = true            {C1 product}      bool C1ProfileVirtualCalls                     = true            {C1 product}      bool C1UpdateMethodData                        = true            {C1 product}      intx CompilationRepeat                         = 0               {C1 product}      bool LIRFillDelaySlots                         = false           {C1 pd product}      intx SafepointPollOffset                       = 256             {C1 pd product}      bool TimeLinearScan                            = false           {C1 product}      intx ValueMapInitialSize                       = 11              {C1 product}      intx ValueMapMaxLoopSize                       = 8               {C1 product}  Enjoy JIT'ing.

Many Java Developers often ask what are the flag options available for C1 and C2 Compilers or what are the flag options available for JIT compilers. Though most of the time our slides will cover some...

Java

Lightweight and Heavyweight components - Mess it !

So, if you are a Swing Developer, you have heard many stories where someone messed up Lightweight component with Heavyweight component. In one line " A heavyweight componentis one that is associated with its own  native screen resource (commonlyknown as a peer). A lightweight component is one that "borrows" thescreen resource of an ancestor  (which means it has no native resourceof its own -- so it's "lighter")." AWT is all heavyweight, Swing is all lightweight except top level ones like JFrame, JWindow... Now many times you have heard "Don't mix lightweight and heavyweight". What will happen ? Alright, here is a small code : import javax.swing.\*;import java.awt.\*;public class Test extends JPanel {  public Test() {     JComboBox jc = new JComboBox();      JButton btn1 = new JButton("Button1");     Button btn2 = new Button("Button2");     Button btn3 = new Button("Button3");     jc.addItem("France");      jc.addItem("Germany");      jc.addItem("Italy");      jc.addItem("Japan");     add(jc);    add(btn1);    add(btn2);    add(btn3);  }  public static void main(String[] args) {    JFrame frame = new JFrame();    frame.getContentPane().add(new Test());    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.setSize(200, 200);    frame.setVisible(true);  }} Here what you see the output: Now, this is what it happen what you mix lightweight and heavyweight. No way, you can bring the drop down items on top of Button2 !! All Past :) , JDK6 update 12 and JDK7 build 19, the output will be like this:  New JDK release fixed all these problem of mixing lightweight component and heavyweight component. So, don't worry, keep messing :). For more detail, please see this : http://java.sun.com/developer/technicalArticles/GUI/mixing_components/index.html

So, if you are a Swing Developer, you have heard many stories where someone messed up Lightweight component with Heavyweight component. In one line " A heavyweight componentis one that is associated...

Java

Sorting and OpenJDK

If you are looking for sorting algorithms and if you use some sorting algorithm in your code/application/big application, then have a look here. First of all sorting/searching is a classic thing. It take more than 70 percent of your application time.People/Developer/Mathematician do a lot of work on optimizing this work to get Best, best out of best. Early days, JDK used to use QuickSort which is one of the best sorting algorithm and go for a complexity of O(nlogn). But mind it, QuickSort is a recursive algorithm and consume space. Whereas some of the algorithm which has the complexity like O(n\^2) go for less complex in terms of memory. These days our platform varies from small mobile device to a terabyte storage machine. JDK has improved sorting algorithm a lot, but the new one which is the sorting algorithm used in Android are get into OpenJDK. Have a look here: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/jdk7-b76/src/share/classes/java/util/TimSort.java. Code is awesomely understandable but just a small explaination. It start with merge sort, which has effecient complexity of O(nlogn). But when the nodes go too much it merge, it calls binary insertion sorting, which is one of the best for small number of elements. Read this comment : /\*\*\* Sorts the specified portion of the specified array using a binary\* insertion sort.  This is the best method for sorting small numbers\* of elements.  It requires O(n log n) compares, but O(n\^2) data\* movement (worst case).\*........................................ I don't know is there any document available who did the actually benchmarking but if I get time, I would love to do checking with all worst/avg cases. It's a nice and tricky algorithm which take care of time complexity and space complexity both.  

If you are looking for sorting algorithms and if you use some sorting algorithm in your code/application/big application, then have a look here. First of all sorting/searching is a classic thing. It...

Java

Debugging basics and some link - Java

Some simple debugging tools related to Java. These are for those who are new to Java. 1. Application is crashing : Most miserable one. Get your log file, try to analysis log. How to write log file, use Java Logger API.  Java Logger had been introduced in JDK 1.4.2. The most awesome feature of Logger API is that you can use it in production without much overhead. The overhead is controlled by something called level in API. Level goes from FINEST to SEVERE. You can refer to O'Relly Book "Java, In a NutShell". I guess, it covers Logging API into a great detail.Lot many things to know: Standalone application is crashing or web application. Its crashing with -client or -server option, appletviewer or browser, plugin or plugin2.  2. Application Hang: Most prominent reason for Hang is thread related. I don't know too many language but Java handles thread in most graceful way. What we can do when a Java Process or Application Hang:     - Hmm, get stack trace at Java and native level.    - Get to know current thread conditions and their status.    - Try to get core dump. Sometime, application will refuse to give you.    - Get to know machine detail. Almost all OS, use different thread model. Not only that in Solaris, 8 and 9 use different models. Sometime, it narrow down the problem, if you are luck :).How to get all these information. Easy actually. Take help of Java Debugger, jdb(which is a part of JDK). In jdb, you can run the command like threads, thread, dump and many more. Take help of Windbg, if its a windows machine for native level. I find it useful and painful. 3. Your application is drinking memory: There is some memory leak. Best is to use jhat(part of JDK). First take a heap dump by using jmap, jconsole hprof. Pass that heap dump to jhat and it will bring a server and dump all the information. Analyze where most of the memory is going. Writing to track the place from where memory is going. What is GC response on it. Change some arguments of GC and then give a try. There are lot of JDK tools that help in analyzing JVM, threads, memory, process. See the list : http://java.sun.com/javase/6/docs/technotes/tools/Garbage collector play important role in all of them, so always get to know what is best for what:- http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html (Even you know less about GC, you can't resist yourself finishing this page, this is so interesting). In terms of GC, everything is improving day be day and we have new GC, Garbage First aka G1 ready. With Vikram, I had one presentation on G1 in Sun tech days - http://developers.sun.com/events/techdays/presentations/locations-2009/hyderabad/td_hyd_garbagcollector_aroskar_choudhary.pdf.If you have any wired debugging story related to Java, please share :). Also, visit Visual VM which is meant to integrate all the command line tools of JDK.

Some simple debugging tools related to Java. These are for those who are new to Java.1. Application is crashing : Most miserable one. Get your log file, try to analysis log. How to write log file, use...

JavaFX

Progress Indicator - JavaFX !

Probably I missed something. But this is the way we can add indefinite progress indicator with any unpredictable events. Here I am just calling a Web service to show yahoo maps for NY city.Here how progress indicator looks like : Progress Indicator is very small :var pi = ProgressIndicator {    scaleX: 2    scaleY: 2    translateX: 90    translateY: 110    progress: -1    visible: bind vLoad    };Make visibility false when Map is loaded. So, vLoad: false in:onDone: function() {                  Main.status = "Done ...";                  Main.vLoad = false;                } Somehow, I am not getting such a good result. I guess, progress thread stuck when Data loading start. May be because one single thread is doing both work. Here is the code : package progressbarshow;import java.lang.Math;import javafx.scene.control.ProgressIndicator;import javafx.scene.Cursor;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.input.KeyCode;import javafx.scene.input.KeyEvent;import javafx.scene.input.MouseEvent;import javafx.scene.Scene;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;import progressbarshow.MapLocate;var pi = ProgressIndicator {    scaleX: 2    scaleY: 2    translateX: 90    translateY: 110    progress: -1    visible: bind vLoad    };public var status: String = "Start Loading Data...";var ml: MapLocate = MapLocate{zip:"10001"}; // 10001 - Newyork, i guessvar x1: Number = 0;var y1: Number = 0;var im: Image = bind Image {    url: ml.location}public var vLoad = true;var loadingText = Text {    visible: bind vLoad    font: Font {        size: 12    }    x: 30,    y: 70    content: bind status}/\* Image of the map from Yahoo WS \*/var imview = ImageView {    cache: true    translateX: bind x1    translateY: bind y1    image: bind im    cursor: Cursor.MOVE    /\* Navigation from Mouse event\*/    onMouseDragged: function( e: MouseEvent ):Void {        if(e.dragX < 0 and x1 < 0) {            x1 = x1 + 5;        }        if(e.dragX > 0 and Math.abs(x1  -  240) < im.width) {            x1 = x1 - 5;        }        if(e.dragY < 0 and y1 < 0 ) {            y1 = y1 + 5;        }        if(e.dragY > 0 and Math.abs(y1  -  320) < im.height) {            y1 = y1 - 5;        }    }    /\* Navigation from key event \*/    onKeyPressed: function( e: KeyEvent ):Void {        if(e.code == KeyCode.VK_LEFT)        {            if(x1 < 0) {                x1+=10;            }        }        if(                    e.code == KeyCode.VK_RIGHT)        {            if(Math.abs(x1  -  240) < im.width) {                x1-=10;            }        }        if(                    e.code == KeyCode.VK_DOWN)        {            if(Math.abs(y1  -  320) < im.height) {                y1-=10;            }        }        if(e.code == KeyCode.VK_UP)        {            if(y1 < 0) {                y1+=10;            }        }    }};    function run() {      Stage {        title: "Yahoo Map Navigation"        width: 240        height: 320        scene: Scene {            content: [            loadingText, imview,  pi            ]        }    }   } Navigation Code: package progressbarshow;import java.lang.Exception;import javafx.data.pull.PullParser;import javafx.io.http.HttpRequest;/\* Class to show Map from Yahoo Web service, input zip code \*/public class MapLocate {    public var location: String;    public var zip: String;    public var isguid: Boolean = false;    var url = bind "http://local.yahooapis.com/MapsService/V1/mapImage?appid=P6pToNnV34GfP9zgTALgVW3CUTL5qHTnKjz5bLXPikqNjcMZTkF6h1xsnhm.P1WIs3U-&zip={zip}";    var p: PullParser;    var h: HttpRequest;    init {        if (url.length() > 0) {            Main.status = "Reading HTTP request....";            h = HttpRequest {                location: url                onException: function(exception: Exception) {                    print("Please check the internet connectivity/Data Input");                }                onConnecting: function() {                    Main.status = "Connection Established ... "                }                onInput: function(input) {                    Main.status = "Parsing Input request....";                    p = PullParser {                        input: input                        onEvent: function(event) {                            if ((event.type == PullParser.END_ELEMENT)) {                                if (event.qname.name == "Result") {                                    isguid = true;                                    location = event.text;                                }                            }                        }                    };                    p.parse();                    p.input.close();                }                onDone: function() {                  Main.status = "Done ...";                  Main.vLoad = false;                }            };            h.start();        }    }}

Probably I missed something. But this is the way we can add indefinite progress indicator with any unpredictable events. Here I am just calling a Web service to show yahoo maps for NY city.Here how...

JavaFX

Use of ListView - UI Control

A simple example how ListView works in JavaFX 1.2. I guess it need more feature in next release. But it do basic stuff like providing scrollbar if list is long, selected item actions.Something like this : Here is the simple code, in which I am adding text array into a ListView(10-15 lines of code). Hmm, image is currently not supported in ListView but soon it will be. package listviewexample;import javafx.scene.control.ListView;import javafx.scene.Scene;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;import javafx.stage.StageStyle; var te:Text[]; for(i in [0..20]) {     var tt = Text {     font : Font {         size: 24     }     x: 10, y: 30     content: "HelloWorld{i}" } insert tt into te; } var simpleList : ListView = ListView {        translateX: 0        translateY: 0        height: 330        width: 240        }; for(i in [0..20])    insert te[i].content into simpleList.items;Stage {    title: "Simple List"    width: 240    height: 325    style: StageStyle.TRANSPARENT    scene: Scene {        content: [            simpleList        ]    }} For some fancy use of ListView, you can see Rakesh Tweeter application on /samples page. Or Josh "A custom virtual list" on jfxstudio.org. Some UI control make life easy.

A simple example how ListView works in JavaFX 1.2. I guess it need more feature in next release. But it do basic stuff like providing scrollbar if list is long, selected item actions.Something like...

JavaFX

Simple example of Scroll Bar - JavaFX 1.2

ScrollBar - UI Control feature of JavaFX 1.2 . It has been used in lot of samples but if you are finding it tough to grab out the code from sample to use. Here is a simple(simplest actually :) ) code to use scrollBar. I have create array of rectangle and associated scroll bar with it. Something like this : And here is the code : package simplescrolluse;import javafx.scene.control.ScrollBar;import javafx.scene.Group;import javafx.scene.paint.Color;import javafx.scene.paint.LinearGradient;import javafx.scene.paint.Stop;import javafx.scene.Scene;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;import javafx.stage.StageStyle;var rect: Rectangle[];for(i in [0..20]) {    var re = Rectangle {            x: 0            y: 35 \*i  + 28            width: 220, height: 34             fill: LinearGradient {                startX : 0.0                startY : 0.0                endX : 0.0                endY : 1.0                stops: [                    Stop {                        color : Color.web("#0174DF")                        offset: 0.0                    },                    Stop {                        color : Color.web("#58ACFA")                        offset: 0.5                    },                    Stop {                        color : Color.web("#0174DF")                        offset: 1.0                    },                ]            }            opacity: 0.9            stroke: Color.BLACK             strokeWidth: 1           } insert re into rect;}var scroll = ScrollBar {        translateX: bind 240 - 10        translateY: 44        height: 320 - 65        scaleX: 0.5        blockIncrement: 16        clickToPosition: false        min: 0        max: 5        vertical: true    };    var rect_height: Integer = 35;    var contactList: Group = Group {        translateY: bind 0 - scroll.value \* rect_height        content: [ rect ]    } ;Stage {    title: "Simple ScrollBar Use"    width: 240    height: 320    style: StageStyle.UNDECORATED    scene: Scene {        content: [            scroll, contactList        ]    }} Please let me know if you stuck in any complication with ScrollBar. Actually it looks easy but scroll bar is a complicated thing. Have fun !

ScrollBar - UI Control feature of JavaFX 1.2 . It has been used in lot of samples but if you are finding it tough to grab out the code from sample to use. Here is a simple(simplest actually :) ) code...

JavaFX

Hyperlink to URL

It's a long time being blogging. Actually not done anything new from long time :). Here is one simple concept which some guys asked me. We have provided hyperlink API in JavaFX 1.2 but some of us struggled to open a URL using hyperlink API. Hmm, 2 ways to do it actually.  No1 : Use the Desktop API of JDK6. It's simple to use. One example is here. So, very basic code will go like this : package sample2;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.scene.control.\*;import java.net.\*;Stage {    title: "HyperLink to URL"    width: 240    height: 320    scene: Scene {        content: [            Hyperlink{                translateY: 160                translateX: 40                width: 150                text: bind "Visit javafx Samples! "                action: function():Void{                    java.awt.Desktop.getDesktop().browse(new URI("http://javafx.com/samples"));                }            }        ]    }} So, 2 things for running this code. First,Desktop API has been added in JDK6, so this code won't run on JDK5. Second, Add rt.jar(rt.jar of JDK6) file in the Libraries if you are using Netbeans No2 : For only JavaFX code, we can use AppletStageExtension like this : package sample1;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.Hyperlink;import javafx.stage.AppletStageExtension;Stage {    title: "Hyperlink to URL"    width: 250    height: 80    scene: Scene {        content: [            Hyperlink {                text: "JavaFX Samples !"                action: function() {                       AppletStageExtension.showDocument("http://javafx.com/samples");                }            }        ]    }} In this case, you cant send hyperlink from Desktop Application, but it will work fine for applet or Browser application. So, best is to use this and then use our normal funda : if {__PROFILE__}" != "browser") --> use the Desktop API code. What you say :). Please let me know if there is any issue in the code ! Or also if there is any better way to do this.

It's a long time being blogging. Actually not done anything new from long time :). Here is one simple concept which some guys asked me. We have provided hyperlink API in JavaFX 1.2 but some of us...

JavaFX

Small code for PieChart...but !

As already discussed, JavaFX 1.2 provide API set for Charts and Graphs. Though I decided to put my hand dirty in writing one 3D piechart from my own. With mine, you will get additional feature of explode in and out feature :). Well, action can be written with the existing chart API and I guess explode feature will also come soon. Making 3D Pie chart is nothing but layering of 2D Pie Chart and here goes a small code : Slice.fx package piechart3d;import java.lang.Math;import javafx.animation.Interpolator;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.scene.CustomNode;import javafx.scene.Group;import javafx.scene.input.MouseEvent;import javafx.scene.Node;import javafx.scene.paint.Color;import javafx.scene.paint.LinearGradient;import javafx.scene.paint.Stop;import javafx.scene.shape.Arc;import javafx.scene.shape.ArcType;/\*\* \* @author Vaibhav Choudhary \*/public class Slice extends CustomNode {    public var color: Color;    public var sAngle: Number = 0.0;    public var len: Number = 0.0;    public var xt = 0.0;    public var yt = 0.0;    function explodout():Boolean {        var t = Timeline {            repeatCount: 1            keyFrames: [                KeyFrame {                    time: 0.25s                    canSkip: true                    values: [                        xt =>                        30 \* Math.cos(2  \*  Math.PI  \*  (sAngle  +  len  /  2)  /  360) tween Interpolator.EASEBOTH,                        yt =>                        -30 \* Math.sin(2  \*  Math.PI  \*  (sAngle  +  len  /  2)  /  360) tween Interpolator.EASEBOTH                    ]                }            ]        }        t.play();        return true    }    function explodein():Boolean {        var t1 = Timeline {            repeatCount: 1            keyFrames: [                KeyFrame {                    time: 0.25s                    canSkip: true                    values: [                        xt => 0,                        yt => 0                    ]                }            ]        }        t1.play();        return true    }    public override function create(): Node {        return Group {            blocksMouse: true            translateX: bind xt            translateY: bind yt            onMouseClicked: function( e: MouseEvent ):Void {                if(xt == 0 and yt == 0) {                    explodout();                }                            else                explodein();            }            content: for(num in [0..25]) {[                    Arc {                        stroke: color                        cache: true                        fill: color                        translateX: 0                        translateY: (num + 1) \* 1                        centerX: 250                        centerY: 250                        radiusX: 150                        radiusY: 60                        startAngle: bind sAngle                        length: bind len                        type: ArcType.ROUND                    }                    Arc {                        cache: true                        fill: LinearGradient {                            startX: 0.3                            startY: 0.3                            endX: 1.0                            endY: 1.0                            stops: [                                Stop {                                    color: color                                    offset: 0.0                                },                                Stop {                                    color: Color.WHITE                                    offset: 1.0                                },                            ]                        }                        centerX: 250                        centerY: 250                        radiusX: 150                        radiusY: 60                        startAngle: bind sAngle                        length: bind len                        type: ArcType.ROUND                    },                ]            }        };    }} Main.fx:package piechart3d;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.stage.Stage;/\*\* \* @author Vaibhav Choudhary \*/var slice1: Slice = Slice{color: Color.YELLOWGREEN, sAngle:0, len: 45};var slice2: Slice = Slice{color: Color.BLUEVIOLET, sAngle:45, len: 80 };var slice3: Slice = Slice{color: Color.PALETURQUOISE, sAngle:125, len: 80 };var slice4: Slice = Slice{color: Color.DARKORANGE, sAngle:205, len: 100 };var slice5: Slice = Slice{color: Color.FIREBRICK, sAngle:305, len: 55};Stage {    title: "Pie Chart - 3D"    width: 550    height: 580    scene: Scene {        fill: Color.WHITE        content:[           slice2, slice1,slice5,slice3,slice4        ]     }    } Anything here can be made generic to any extend. There is a for loop of 0..25 in Slice.fx which speaks about the thickness of chart :) and some mathematics in timeline speaks about explode feature. Now if you compare this with PieChart that comes in API, you will see this has some jerky corners + Color combination is not as soluble. How that has been made is secret :). JNLP Run :

As already discussed, JavaFX 1.2 provide API set for Charts and Graphs. Though I decided to put my hand dirty in writing one 3D piechart from my own. With mine, you will get additional feature...

Java

Browser + Drag + Feature + JavaFX + Profile + Many more :)

Final destination for us is death and final destination of a JavaFX application is Browser. So, we should know what all things we can do with an application, JavaFX application, in browser. Here are some : 1. Understand when our code will run on browser and when on Desktop/Mobile and optimize the code. Here is a small one : package appletshow;import javafx.scene.\*;import javafx.scene.input.MouseEvent;import javafx.scene.paint.\*;import javafx.scene.shape.\*;import javafx.scene.text.\*;import javafx.stage.\*;/\*\* \* @author Vaibhav Choudhary \*/var textContent = "Hello JavaFX in applet World";var subtext = "Drag me out for this example(Alt->Drag)";var vis = false;var s: Stage = Stage { title: "Applet Show" width : 600 height : 200 style: StageStyle.TRANSPARENT scene : Scene { fill: Color.BLACK content: [ Text { content: textContent x: 25 y:35 fill: Color.WHITE font: Font{size: 24} } Text { content: subtext x: 25 y:55 fill: Color.WHITE font: Font{size: 14} } Rectangle { x: 560 y: 10 width: 20 height: 20 arcHeight:5 arcWidth: 5 stroke:Color.GRAY strokeWidth: 2 fill: Color.TRANSPARENT visible: bind ("{__PROFILE__}" != "browser") onMouseClicked: function(e: MouseEvent): Void { s.close(); } } Text { fill: Color.WHITE visible: bind ("{__PROFILE__}" != "browser") font : Font { name:"Arial Bold" size: 14 } x: 567, y: 25 content: "x" } , ] }} Close button will be visible only in browser not in desktop/mobile. So, this is logical, close button should not be in Browser. 2. Remeber, we have draggable feature and things can change from applet inside the browser and when it has been dragged out :). Now, I want again that when I dragged my applet out of the browser, I get a close button which is logical again, because a dragged application is like a desktop application. So, here we go :) package appletshow2;import javafx.scene.\*;import javafx.scene.input.MouseEvent;import javafx.scene.paint.\*;import javafx.scene.shape.\*;import javafx.scene.text.\*;import javafx.stage.\*;var textContent = "Hello JavaFX in applet World";var subtext = "Drag me out for this example(Alt->Drag)";var vis = false;var s: Stage = Stage { title: "Applet Show" width : 600 height : 200 style: StageStyle.TRANSPARENT scene : Scene { fill: Color.BLACK content: [ Text { content: textContent x: 25 y:35 fill: Color.WHITE font: Font{size: 24} } Text { content: subtext x: 25 y:55 fill: Color.WHITE font: Font{size: 14} } Rectangle { x: 560 y: 10 width: 20 height: 20 arcHeight:5 arcWidth: 5 stroke:Color.GRAY strokeWidth: 2 fill: Color.TRANSPARENT visible: bind vis onMouseClicked: function(e: MouseEvent): Void { s.close(); } } Text { fill: Color.WHITE visible: bind vis font : Font { name:"Arial Bold" size: 14 } x: 567, y: 25 content: "x" } , ] } extensions: [ AppletStageExtension { onDragStarted: function() { vis = true; } onAppletRestored: function() { vis = false; } useDefaultClose: false } ]} Points to remember : a. useDefaultClose : false, it will vanish the default close button else it will be a mess, seeing too many close buttons. b. AppletStageExtension has lot of other features, please check the API. c. Close button should vanish once it goes back into the browser.  3. Ah, now most important about dragging feature. I don't want to drag applet with Alt-> Drag feature, I want it should be draggable in simple style like we do with other application, NO COMPLICATION. Use this :) package shoulddrag;import javafx.lang.FX;import javafx.scene.input.MouseEvent;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.scene.shape.Rectangle;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.AppletStageExtension;import javafx.stage.Stage;import javafx.stage.StageStyle;import javafx.scene.paint.LinearGradient;import javafx.scene.paint.Stop;/\*\* \* @author Vaibhav Choudhary \*/var isApplet = "true".equals(FX.getArgument("isApplet") as String);var inBrowser = isApplet;var dragRect: Rectangle;var draggable = AppletStageExtension.appletDragSupported;dragRect = Rectangle { x: 0 y: 0 width: 240 height: 40 opacity: 0.5 fill: LinearGradient { startX: 0.0 startY: 0.0 endX: 0.0 endY: 1.0 stops: [ Stop { color: Color.BLACK offset: 0.0 }, Stop { color: Color.WHITE offset: 0.3 }, Stop { color: Color.BLACK offset: 1.0 }, ] } onMouseDragged: function(e:MouseEvent):Void { print(inBrowser); stage.x += e.dragX; stage.y += e.dragY; }};var dragTextVisible = bind draggable and dragRect.hover;var can_drag_me_text: Text = Text { content: "You can drag me !" fill: Color.BLACK font: Font { size: 12 embolden: true name: "Arial Bold" } opacity: 1.0 visible: bind dragTextVisible y: 20 x: 15};var stage = Stage { title: "Should Drag" width: 250 height: 280 style: StageStyle.TRANSPARENT scene: Scene { content: [ dragRect, Rectangle { x: 0, y: 40 width: 240, height: 290 fill: Color.BLACK }, can_drag_me_text ] } extensions: [ AppletStageExtension { shouldDragStart: function(e): Boolean { return e.primaryButtonDown and dragRect.hover; } onDragStarted: function(): Void { inBrowser = false; } onAppletRestored: function(): Void { inBrowser = true; } useDefaultClose: true } ]} Some complication are in code, but be relaxed and see, too easy, RIGHT ? Alright ! What more we can add here... Please let me know if there is any issue with any of the code. Thanks !

Final destination for us is death and final destination of a JavaFX application is Browser. So, we should know what all things we can do with an application, JavaFX application, in browser. Here are...

JavaFX

JavaFX Production Suite - Usages

The new samples are more complex than older once. And this is what we want. New features, not only need a sample to showcase but all the sample should be result oriented. Mean to say, it should do something with real world. In the meantime, I can show you how interaction of JavaFX SDK increased with Production Suite.  Lot of samples like Forecasting, BrickBreaker, SnakesNLadders are using Production Suite. They get the FXZ file from the designer and then do the animation job(logic coding) in JavaFX. One I can explain of mine, Forecasting, though this sample is not complete but it uses FXZ file to a great extent. I got all the weather information in FXZ file by Charles, who is the graphics designer of this sample. Now, our idea is to animate weather conditions. According to the condition, we need to thought of animation. For thunder, it looks something like this :  Animation can be viewed in applet but I am just putting an image. Here there are three animation, 1. Shining of Sun 2. Left thunder spark 3. Right thunder spark. Now, I have 5 layers of image in FXZ file, Sun, Sun Glow, Cloud, Left spark, right spark. On the basic of these, we decided what to animate when ! Final point is we need animation like opacity reduction or translation or both or rotating. Content once delivered to us in FXZ file, we can easily interoperable with FX code. The best way is to define layer names in FXZ file and use it in the code.

The new samples are more complex than older once. And this is what we want. New features, not only need a sample to showcase but all the sample should be result oriented. Mean to say, it should...

JavaFX

JavaFX 1.2 : RIA + You

So, finally sweat materialized into product. JavaOne announced the new release of JavaFX 1.2. You are welcome to visit the new cool site of javafx.com. Also visit the sample section, fully loaded with new samples. JavaFX 1.2 release is loaded with enormous features. Detailed list  here. Little bit what I know, let me speak about the changes and the corresponding samples. 1. Set of new UI Controls : Buttons, Sliders, Texts ... bla bla... many more. Please figure out in this nice sample : ProjectManager. Other new samples are also using it like FXAddressBook, StockQuote 2. Chart API : LineChart, AreaChart, BarChart(2D,3D), PieChart(2D,3D), Bubble Chart and many more. Please see the detail in Chart API doc. Samples : Shopping Mashup, Weather Forecasting 3. Persistence Storage: Resource and Storage class has been added. Samples: StickyNotes 4. Start-up performance has been increased around 40 percent. No Sample for it :) or we can saw all sample for it :). 5. Lot of changes in Graphics API's 6. O yes, adding of Asynchronous Operations, last time I was struggling running process in Parallel in JavaFX as it is a single threaded application. Some more things you would like to see : 2 FullScreen Games has been added into samples repo, Reversi Game and SnakesLadders. IMPORTANT POINT : Many times I talk about RIA, and now if you see the sample repo, there are only few samples which are not using any Web Services. Most of it, are taking Data dynamically from Web Services. More things to come ....

So, finally sweat materialized into product. JavaOne announced the new release of JavaFX 1.2. You are welcome to visit the new cool site of javafx.com. Also visit the sample section, fully loaded with n...

JavaFX

Yahoo Map Navigation...JavaFX

Extremely sorry for not responding to the question in few of the last blog posts. Here is the Yahoo Map navigation. I started liking Yahoo Web Service, it is so cool. Please use your App-ID, if you are putting this code somewhere else, because this code uses default Yahoo Key.  Now, any web service work need these API use : PullParser - A parser for structured Data. JDK6 can also do parsing in same way. HttpRequest - Can use for Async HTTP or RestFul web services. This code is so easy and monotonous that you will start copying it after 2-3 go :). Here it goes for Yahoo Map + Navigation code I have added addition here for both key and mouse. JNLP for the same :  Main.fx : package yahoomapnavigation;import java.lang.Math;import javafx.scene.Cursor;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.input.KeyCode;import javafx.scene.input.KeyEvent;import javafx.scene.input.MouseEvent;import javafx.scene.Scene;import javafx.stage.Stage;import yahoomapnavigation.MapLocate;/\*\* \* @author Vaibhav \*/var ml: MapLocate = MapLocate{zip:"10001"}; // 10001 - Newyork, i guessvar x1: Number = 0;var y1: Number = 0;var im: Image = bind Image { url: ml.location}/\* Image of the map from Yahoo WS \*/var imview = ImageView { cache: true translateX: bind x1 translateY: bind y1 image: bind im cursor: Cursor.MOVE /\* Navigation from Mouse event\*/ onMouseDragged: function( e: MouseEvent ):Void { if(e.dragX < 0 and x1 < 0) { x1 = x1 + 5; } if(e.dragX > 0 and Math.abs(x1 - 240) < im.width) { x1 = x1 - 5; } if(e.dragY < 0 and y1 < 0 ) { y1 = y1 + 5; } if(e.dragY > 0 and Math.abs(y1 - 320) < im.height) { y1 = y1 - 5; } } /\* Navigation from key event \*/ onKeyPressed: function( e: KeyEvent ):Void { if(e.code == KeyCode.VK_LEFT) { if(x1 < 0) { x1+=10; } } if( e.code == KeyCode.VK_RIGHT) { if(Math.abs(x1 - 240) < im.width) { x1-=10; } } if( e.code == KeyCode.VK_DOWN) { if(Math.abs(y1 - 320) < im.height) { y1-=10; } } if(e.code == KeyCode.VK_UP) { if(y1 < 0) { y1+=10; } } }};Stage { title: "Yahoo Map Navigation" width: 240 height: 320 scene: Scene { content: [ imview ] }}MapLocate.fx :package yahoomapnavigation;import java.lang.Exception;import javafx.data.pull.PullParser;import javafx.io.http.HttpRequest;/\*\* \* @author Vaibhav \*//\* Class to show Map from Yahoo Web service, input zip code \*/public class MapLocate { public var location: String; public var zip: String; public var isguid: Boolean = false; var url = bind "http://local.yahooapis.com/MapsService/V1/mapImage?appid=P6pToNnV34GfP9zgTALgVW3CUTL5qHTnKjz5bLXPikqNjcMZTkF6h1xsnhm.P1WIs3U-&zip={zip}"; var p: PullParser; var h: HttpRequest; init { if (url.length() > 0) { h = HttpRequest { location: url onException: function(exception: Exception) { print("Please check the internet connectivity/Data Input"); } onInput: function(input) { p = PullParser { input: input onEvent: function(event) { if ((event.type == PullParser.END_ELEMENT)) { if (event.qname.name == "Result") { isguid = true; location = event.text; } } } }; p.parse(); p.input.close(); } onDone: function() { } }; h.enqueue(); } }}</pre> Please let me know if there is any issue, with JNLP or code :). Have fun !

Extremely sorry for not responding to the question in few of the last blog posts. Here is the Yahoo Map navigation. I started liking Yahoo Web Service, it is so cool. Please use your App-ID, if you are...

JavaFX

Image of the Day - NASA + JavaFX

In last blog entry, we talked to have some blogs on Web Service to show how things go. Here is one of the simplest. JavaFX is moving towards it's next release and work is ON. One of my friends came to my desk and he saw some animation of weather going here and there. He asked me " Is it some scientific data, data from NASA or something like that, if not what is this animation all about". Meantime, I checked the RSS feeds/WebService by NASA and I use one here to get something called "Image of the Day". Its a big size image and so decide to showcase fullscreen example as well. Here goes the small code : //Main.fx package nasaimage;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.image.ImageView;import javafx.scene.image.Image;import javafx.scene.input.MouseEvent;import javafx.scene.Node;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.scene.text.TextAlignment;/\*\* \* @author Vaibhav \*/var s: Stage;public var vText: Boolean = true;var ly: LocationY = LocationY{};var im = ImageView {    fitHeight: bind s.height    fitWidth: bind s.width    image: bind Image {        url: ly.urlImage    }}var rect = Rectangle {   blocksMouse: true   x: bind s.width - 25   y: 20   arcHeight: 4   arcWidth: 4   width: 20,   height: 20   stroke: Color.GRAY   strokeWidth: 2   onMouseClicked: function( e: MouseEvent ):Void {       FX.exit();   }}/\* close button 'x' in title bar \*/var close = Text {   fill: Color.WHITE   font: Font {       name: "Arial Bold"       size: 18   }   x: bind s.width - 20   y: 35   content: "x"}var loadingText = Text {   visible: bind vText   fill: Color.BLACK   font: Font {       name: "Arial Bold"       size: 20   }   x: 20   y: 20   content: "Loading Image from NASA WebService..."}function run() {s = Stage {    title: "Nasa Image"    width: 300    height: 300    fullScreen: true        scene: Scene {        content: [            loadingText,im, rect, close         ]    }}} //LocationY.fx package nasaimage;import java.lang.Exception;import javafx.data.pull.PullParser;import javafx.data.xml.QName;import javafx.io.http.HttpRequest;/\*\* \* @author Vaibhav \*/public class LocationY {    public var urlImage:String;    var url = bind "http://www.nasa.gov/rss/lg_image_of_the_day.rss";    var p: PullParser;    var h: HttpRequest;    init {        if (url.length() > 0) {            h = HttpRequest {                location: url                onException: function(exception: Exception) {                    print("Please check the internet connectivity or Data Input");                }                onInput: function(input) {                    p = PullParser {                        input: input                        onEvent: function(event) {                            if ((event.type == PullParser.END_ELEMENT)) /\* and (event.qname.name == "current_conditions")) \*/{                                if (event.qname.name == "enclosure") {                                    urlImage = event.getAttributeValue(QName{name:"url"});                                 }                            }                        }                    };                    p.parse();                    p.input.close();                }                onDone: function() {                Main.vText = false;                }            };            h.start();        }    }} Don't ask me why I am using LocationY.fx as filename. Sometime back, I made my first webservice with name LocationY and from that time, I am copying the same file. Last day Photo was more awesome than this. I guess it was something related with stars :). As talked in the prev. blog about the use of OnDone() method, here it is. Before loading of image, you will see a text   'Loading Image from NASA WebService...'. This text vanishes when image get loaded because we have called its visible: false in OnDone() method of HTTP. I hope you love this short code and start of webservices. Thanks to NASA website to provide this RSS feed :).

In last blog entry, we talked to have some blogs on Web Service to show how things go. Here is one of the simplest. JavaFX is moving towards it's next release and work is ON. One of my friends came to...

JavaFX

Take care of Basic User Interface - JavaFX

For a developer perspective, I always appreciate the work of Graphics Designer. Immense level of smoothness, simple though beautiful, delicacy in every movement and most important fulfill the functionality in most easier way. Though we all can't think like a UE or a Graphics Designer but we can maintain the correct functionality in code. Some code which I have seen in last one month are awesome but some simple points are missing not because they are tough to write but because we forgot to write. 1. Use the correct cursor when required :  Like if its a button or a Hyperlink, cursor should be Cursor.HAND like this code : package cursorsample;import javafx.scene.Cursor;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.scene.shape.Rectangle;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;Stage{    title: "Button Cursor"    width: 250    height: 280    scene: Scene{        content: [            Rectangle {                cursor: Cursor.HAND                x: 10,                y: 10                arcHeight: 10                arcWidth: 10                width: 100,                height: 30                fill: Color.BLACK            },            Text {                fill: Color.WHITE                font: Font {                    name: "Arial Bold"                    size: 14                }                x: 15,                y: 30                content: "Hand Cursor"            }        ]    }} If you are navigating inside the map or graph or if you are dragging things out. Cursor is supposed to be Cursor.MOVE. Please check the complete list supported in FX: http://java.sun.com/javafx/1.1/docs/api/javafx.scene/javafx.scene.Cursor.html 2. Simple opacity Game : Changing the opacity with simple values can make the UI rich. Simple code like this : var opacity = 0.6; onMouseEntered: function( e: MouseEvent ):Void {                    opacity = 1.0;                }                onMouseExited: function( e: MouseEvent ):Void {                    opacity = 0.6;                }  and bind the opacity of rectangle with opacity variable. 3. Gradient give life : "My Button" is simple but you will find it much better than only Black or only GRAY. Same way, you can make it more rich with filling correct gradient. Most of the time we find it a problem in setting Gradient color. My simple formula says, take 2 color of same family and try to mix. Never mix color like RED and GREEN. Mix LIGHTGREEN and DARKGREEN, RED and DARKRED, BLUE and AQUA. Using these, we can see effects like this :  4. Gradient at title bar -> I love to write custom title bar in place of OS defaults which always gives a feeling that I am living in old age. Color in title bar can be made cool with gradient like : This is simple DARKGREEN, BLACK and DARKGREEN linear gradient. Though, I am misusing the close button concept here. Close button should not be green in color, preferable color is RED. 5. If we want it to be simple: If application itself is too complex and we want to minimize the cost of gradient, colors. Best is to go with simplicity. A black background with white text is one of the awesome combination.  6. Web services or HTTP request : If we are using PullParser and HTTP, onDone method is one of the important places for everything. Consider on a button click you called a web service and web service takes sometime and showed the output. In the middle, you need to show a screen to user saying "We called this web service and it will take sometime", else user will impatiently close the window. So, waitingText.visible = true when mouse click ! In onDone() {   waitingText.visible = false; } Soon, we will have more example on this :). That's it.  Have fun with JavaFX !

For a developer perspective, I always appreciate the work of Graphics Designer. Immense level of smoothness, simple though beautiful, delicacy in every movement and most important fulfill the...

JavaFX

JavaFX + Web Service + Maps + Navigation

Just a small demo of JavaFX + Web Services. From JavaFX, its quite easy to work on Web Services like maps, search, pictures .. There are lot of Web services demo in the sample space.  Here I have contact list of person, which has name, email ID, phone no, address and thumbnail images. Everything has a different work but here we are willing to see the address work. On clicking contact list's, will show me his location in maps. Actually there are two ways to do that, fast way and good way. We can store the maps in Database and use it when required, other is we call the web service and take the map on demand from Yahoo or Google API, which will be slow. So, we will go with good way. Considering only one contact. Some fancy stuff, like clicking the + sign will open address option. Now, on clicking the address, we will call the yahoo maps API for showing the location of the person Joseph J. Actually its a mobile application, and can be viewed in mobile as well(just that I am not putting image). So, in basic code of Map show, we did : // in place of Sunnyvale and CA, it will be {city} and {state} which will be the variables and passed from main code. var url = bind "http://local.yahooapis.com/MapsService/V1/mapImage?appid=GetApp;city=Sunnyvale&state=CA";   var p: PullParser;   var h: HttpRequest;   init {           if (url.length() > 0) {           h = HttpRequest {               location: url                onException: function(exception: Exception) {                }                 onInput: function(input) {                    p = PullParser {                       input: input                       onEvent: function(event) {                            if ((event.type == PullParser.END_ELEMENT)) {                               if (event.qname.name == "Result") {                                   location = event.text; //this will give a URL for image                               }                          }                       }                   };                   p.parse();                   p.input.close();      ....... Lot of further code. Important of it is OnDone method where we have to write some code of cleaning or loading prev. data. I have also embed my long back code of navigation, which will help us into navigation in the map. Ignore some minor mistakes, have a look at the jnlp: Soon, I will post the whole application with code, but the basic idea is simple and can be doable. 

Just a small demo of JavaFX + Web Services. From JavaFX, its quite easy to work on Web Services like maps, search, pictures .. There are lot of Web services demo in the sample space.  Here I have...

Java

Timelines - Ease to Use in JavaFX

JavaFX being an easy language, one complex part is to write proper timeline for animation. Though its quite easy but as beginner I feel problem sometime. And sometime as a Java Developer, we start demanding those things which are generally done by the concept of multi-threading in Java. Remember, JavaFX is single threaded application. So, this is what I generally follow. Say, If I have a class Ball, which has a circle and every ball has a timeline for its own. Now, if you want One ball move after another ball, I write a master timeline in Main file and there we write something like this :var t = Timeline {    repeatCount: 1    keyFrames: [         KeyFrame { time:0s action: function(){ t1.t.playFromStart(); } },         KeyFrame { time:1s action: function(){ t2.t.playFromStart(); } },    ]}Where there is an animation of 1s in t1.t.playFromStart(); So, the next timeline call goes at 1s, means finishing at first one. If you want some initial delay, you can write :var t = Timeline {    repeatCount: 1    keyFrames: [         KeyFrame { time:1s action: function(){ t1.t.playFromStart(); } },         KeyFrame { time:2s action: function(){ t2.t.playFromStart(); } },    ]}Means, dont do anything from 0s to 1s.But, It is possible that you messed up after sometime. For that, you need to check the "javafx.animation.transition" package, one of the awesome packages in FX API's. Though, example is everywhere in API Doc. I just show a small one, copied from the API' example itself. First car will fade, then move left and right, then rotate, then move again and then zoom. Code for assistance : 1. Main for timeline problem. 2. Time class for timeline problem 3. Transitions Main Class.

JavaFX being an easy language, one complex part is to write proper timeline for animation. Though its quite easy but as beginner I feel problem sometime. And sometime as a Java Developer, we start...

Java

Spot Light at spot - JavaFX

There are lot of ways, you can use Lighting effects in JavaFX. All of them have its own use like Spot Light, Distant Light or Point Light. One small sample to show how Spot Light works. Run the JNLP : Here is the code : package lightingeffects;import javafx.animation.Interpolator;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.scene.effect.GaussianBlur;import javafx.scene.effect.light.SpotLight;import javafx.scene.effect.Lighting;import javafx.scene.Group;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.scene.shape.Circle;import javafx.scene.text.Font;import javafx.scene.text.FontWeight;import javafx.scene.text.Text;import javafx.scene.text.TextOrigin;import javafx.stage.Stage;/\*\* \* @author Vaibhav Choudhary \*/var distance = -20.0;var t = Timeline {    repeatCount: 200    autoReverse: true    keyFrames: [        KeyFrame {            time: 6s            canSkip: true            values: [                distance => 200.0 tween Interpolator.LINEAR            ]        }    ]}t.play();Stage {    title: "Lighting Effects"    width: 240    height: 250    scene: Scene {        fill: Color.BLACK        content: [            Group {                var t: Text;                content: [                    Circle {                        translateX: bind distance                        centerX: 20,                        centerY: 45                        radius: 30                        stroke: Color.RED                        strokeWidth: 2                        effect: GaussianBlur {                            radius: 10                        }                    }                    t = Text {                        translateX: 10                        translateY: 20                        effect: Lighting {                            light: SpotLight {                                x: bind distance                                y: 0                                z: 100                                pointsAtX: bind distance                                pointsAtY: 0                                pointsAtZ: 0                                specularExponent: 4                            }                            surfaceScale: 3                        }                        textOrigin: TextOrigin.TOP                        x: 10                        y: 10                        content: "SpotLight"                        fill: Color.RED                        font: Font.font(null, FontWeight.BOLD, 40);                    }                ]            }            Group {                content: [                    Circle {                        translateX: bind distance                        centerX: 20,                        centerY: 145                        radius: 30                        stroke: Color.GREEN                        strokeWidth: 2                        effect: GaussianBlur {                            radius: 10                        }                    }                    Text {                        translateX: 10                        translateY: 120                        effect: Lighting {                            light: SpotLight {                                x: bind distance                                y: 0                                z: 100                                pointsAtX: bind distance                                pointsAtY: 0                                pointsAtZ: 0                                specularExponent: 4                            }                            surfaceScale: 3                        }                        textOrigin: TextOrigin.TOP                        x: 10                        y: 10                        content: "SpotLight"                        fill: Color.GREEN                        font: Font.font(null, FontWeight.BOLD, 40);⁞                    }                ]            },        ]    }}

There are lot of ways, you can use Lighting effects in JavaFX. All of them have its own use like Spot Light, Distant Light or Point Light. One small sample to show how Spot Light works. Run the JNLP : He...

Java

Easy to use - A Block of JavaFX !

Somewhere in someone blog, I read this "Complex thing should be doable and simple things should be simple" - this is what the power of a Language. Many of us have seen lot of Samples in JavaFX and my favorites are those in which complex things are done quite easy, like PhotoFlip. http://www.javafx.com/samples/PhotoFlip/index.html. You can see how complex calculation goes for a perspective transform.Using it in a simpler form, I tried to write Cascade transformed Frames, which looks something like this :You can play with 2 buttons. Sorry for not making some flashy button, I simple used Swing Buttons. By code is little buggy, so bear with it. - Moving Mouse on any frame, will make it front.- Close button will close that frame. (It is only possible in non-perspective mode).- Top bar can be useful for dragging the frames(again good at non-perspective mode, in perspective mode, use the left most corner to  drag it, you can figure out why is so ? :) ).- Text will be as clear as it was in original mode.- Sharing common reason in case of toFront() make the effect little flckry.(One problem solved, thanks for José Miguel in comment section - Code changed)Its all in around 100-150 lines of code.  Feel free for suggestions. This can be used for multi-frame work like showing Car models, parts of engine. Code : Main.fx package cascade;import cascade.Frame;import javafx.ext.swing.SwingButton;import javafx.scene.Group;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.stage.Stage;/\*\* \* @author Vaibhav Choudhary \*/var bt: Frame = Frame{ x: 20, y: 140 };var bt1: Frame = Frame{ x: 100, y: 220};var bt2: Frame = Frame{ x: 180, y: 300};var gp = Group {};insert bt into gp.content;insert bt1 into gp.content;insert bt2 into gp.content;Stage {    title: "Application title"    width: 550    height: 580    scene: Scene {        fill: Color.GRAY        content: [            gp            SwingButton {                translateX: 10                translateY: 10                text: "Transform"                action: function() {                    bt1.t.playFromStart();                    bt.t.playFromStart();                    bt2.t.playFromStart();                }            }            SwingButton {                translateX: 100                translateY: 10                text: "Normal"            action: function() {                bt1.t.rate = -1;    bt1.t.play();                bt2.t.rate = -1;    bt2.t.play();                bt.t.rate = -1;     bt.t.play();            }            }        ]    }}Frame.fxpackage cascade;import javafx.animation.Interpolator;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.scene.CustomNode;import javafx.scene.effect.PerspectiveTransform;import javafx.scene.Group;import javafx.scene.input.MouseEvent;import javafx.scene.Node;import javafx.scene.paint.Color;import javafx.scene.paint.LinearGradient;import javafx.scene.paint.Stop;import javafx.scene.shape.Rectangle;import javafx.scene.text.Font;import javafx.scene.text.Text;/\*\* \* @author Vaibhav Choudhary \*/public class Frame extends CustomNode {    public var startx: Number;    public var starty: Number;    public var x: Number;    public var y: Number;    var distX: Number;    var distY: Number ;    public var clip_ = 0.0;    public var t = Timeline {        repeatCount: 1        keyFrames: [            KeyFrame {                time: 1s                canSkip: true                values: [                    clip_ => -150.0 tween Interpolator.LINEAR                ]            }        ]    }    public var t_rev = Timeline {        repeatCount: 1        keyFrames: [            KeyFrame {                time: 1s                canSkip: true                values: [                    clip_ => 0.0 tween Interpolator.LINEAR                ]            }        ]    }    public override function create(): Node {        return Group {             effect: PerspectiveTransform {                ulx: 0                uly: 0                urx: 300                ury: bind clip_                lrx: 300                lry: bind clip_ + 150                llx: 0                lly: 150            }            cache: true            translateX: bind x + startx            translateY: bind y + starty            content: [                Rectangle {                    x: 0,                    y: 0                    opacity: 0.6                    width: 300                    height: 150                    fill: Color.BLACK                    onMouseMoved: function( e: MouseEvent ):Void {                        this.toFront();                    }                },                Text {                    fill: Color.WHITE                    font: Font {                        size: 14                        name: "Arial Bold"                    }                    x: 10,                    y: 40                    content: "I am living on a 3D Frame. You can \\n  transform me using the Transform \\n Button at the top, "                    "you can set \\n me normal using normal button "                }                Rectangle {                    x: 1,                    y: 1                    width: 299,                    height: 20                    opacity: 0.8                    fill: LinearGradient {                        startX: 0.0                        startY: 0.0                        endX: 0.0                        endY: 1.0                        stops: [                            Stop {                                color: Color.GRAY                                offset: 0.0                            },                            Stop {                                color: Color.BLACK                                offset: 1.0                            },                        ]                    }               onMousePressed: function (e:MouseEvent) : Void{ distX = startx; distY = starty; } onMouseDragged: function( e: MouseEvent ):Void { startx =distX + e.dragX; starty =distY + e.dragY; }                },                Rectangle {                    x: 280,                    y: 3                    width: 15,                    height: 15                    opacity: 0.7                    onMouseClicked: function( e: MouseEvent ):Void {                        this.visible = false;                    }                    fill: LinearGradient {                        startX: 0.0                        startY: 0.0                        endX: 0.0                        endY: 1.0                        stops: [                            Stop {                                color: Color.ORANGE                                offset: 0.0                            },                            Stop {                                color: Color.DARKRED                                offset: 0.5                            },                            Stop {                                color: Color.ORANGE                                offset: 1.0                            },                        ]                    }                    arcHeight: 5                    arcWidth: 5                },                Text {                    font: Font {                        size: 20                    }                    x: 283,                    y: 17                    content: "x"                }            ]        };    }} View the JNLP here :)

Somewhere in someone blog, I read this "Complex thing should be doable and simple things should be simple" - this is what the power of a Language.Many of us have seen lot of Samples in JavaFX and my...

Java

Flexible writing - JavaFX

Writing flexible code is always good. Though I myself write lot of hard coded stuff but nothing wrong in giving good lecture :D. Weeks back I planned to make flexible template in JavaFX, so that we all can use it by just writing one line of code and that is making an instance of that template in our main file. In general the code we write comes with OS frame like on Windows XP it will come with blue frame and close button, min/max buttons, but for good graphics its between to use own template :) and off course it will work on mobile too. Here are some examples :  So, I have just created a close button on which we call FX.exit(), nothing else. If we can customize the close button, say hmm to save the data or to save the position of the application. Most of the time it happens, we want the application to open at same position where we dragged it last time. Important thing to notice is the upper rectangle I mean the title bar adjust the length from its own. So, even the landspace(90 degree rotating the mobile) will give us the correct template form(title bar). I agree, it should be small in case of mobile, and even that can be manageable with code(I have not done in this example).  How to do this can be understandable in 3 basics steps : 1. Define scene as an instance and use that inside stage like this : public var s = Scene {    height: 200    width: 200    fill: Color.GRAY    content: [        Text {            font: Font {                size: 20            }            x: 10,            y: 100            content: "Application content"        }    ]}; and then: Stage {        title: "Flexible Themes"        style: StageStyle.TRANSPARENT        width: 240        height: 320        scene: s ...... 2. Everything will be effected with scene width and height. So, take this in a var. like : public var width = bind s.width;public var height = bind s.height; Now, every component, like rectangle, arc, circle will be properly bind with width and height. Changes width and height will change all the component in relative term. So, rectangle(border line) is : Rectangle {                    x: 0,                    y: 0                    width: bind sceneWidth - 1                    height: bind sceneHeight - 1                    fill: Color.TRANSPARENT                    stroke: Color.BLACK                    strokeWidth: 2                },  where, var sceneWidth = bind Main.width;var sceneHeight = bind Main.height; This code is written in different file so you need to take width and height from main file. This is title bar rectangle(the blue and the green) : Rectangle {                    x: 1,                    y: 1                    width: bind sceneWidth - 1,                    height: 30                    opacity: 0.8                    fill: LinearGradient {                        startX: 0.0                        startY: 0.0.... So, height is hard coded here but it should vary according to the size of window. For small window like mobile screen we need to reduce it with some factor. 3. Since Main is used as many place, the compiler will confuse with the entry point, so write the main stage code in function run(). Like: function run() {    var s1 = Stage {        title: "Flexible Themes"        style: StageStyle.TRANSPARENT        width: 240        height: 320        scene: s    }} Here are the files : Main File (Please rename this file to Main.fx, else you will get some problem) Blue Theme, Green Theme  There can be lot to do with Themes, like adding min/max button, giving drag option which is default in OS Frames or save option as we already mentioned.  Please let me know if I missed something :). Thanks to Josh for making it possible for all screen.

Writing flexible code is always good. Though I myself write lot of hard coded stuff but nothing wrong in giving good lecture :D. Weeks back I planned to make flexible template in JavaFX, so that we...

Java

Different text effects in JavaFX

Some of the way, we can make fancy text. There are lot of good way but these are few of them. If you really want to make it fancy then please do some R&D with these API's used in this code. Here is a small code: package addingfontinstyle;import javafx.scene.effect.DropShadow;import javafx.scene.effect.GaussianBlur;import javafx.scene.effect.light.DistantLight;import javafx.scene.effect.light.SpotLight;import javafx.scene.effect.Lighting;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.scene.text.Font;import javafx.scene.text.FontWeight;import javafx.scene.text.Text;import javafx.scene.text.TextOrigin;import javafx.stage.Stage;Stage {    title: "Text In Style"    width: 450    height: 500    scene: Scene {        content: [            Text {                effect: DropShadow {                    offsetX: -10                    offsetY: -10                }                font: Font {                    name: "Arial"                    letterSpacing: 0.20                    size: 50                }                fill: Color.YELLOWGREEN                stroke: Color.GREEN,                strokeWidth: 3                x: 15,                y: 80                content: "Hello World"            },            Text {                effect: Lighting {                    light: DistantLight {                        azimuth: -135                        elevation: 30                    }                    surfaceScale: 5                }                x: 10                y: 200                content: "Hello World"                fill: Color.RED                font: Font {                    name: "Arial Bold"                    letterSpacing: 0.20                    size: 50                }            },            Text {                effect: Lighting {                    light: SpotLight {                        x: 0                        y: 100                        z: 50                        pointsAtX: 400                        pointsAtY: 0                        pointsAtZ: 0                        specularExponent: 2                    }                    surfaceScale: 5                }                textOrigin: TextOrigin.TOP                x: 10                y: 300                content: "Hello World"                fill: Color.RED                font: Font {                    name: "Arial Bold"                    letterSpacing: 0.20                    size: 50                }            },            Text {                effect: GaussianBlur {                }                x: 10                y: 400                content: "Hello World"                fill: Color.GREEN                font: Font {                    name: "Arial Bold"                    letterSpacing: 0.20                    size: 50                }            }        ]    }}

Some of the way, we can make fancy text. There are lot of good way but these are few of them. If you really want to make it fancy then please do some R&D with these API's used in this code. Here is a...

Java

Putting effect in effective way...JavaFX

With me, it happens most of the time. The basic code is over and I stuck in giving a good color to a button or a text. Now a day, a good UI is as required as basic functionality. In my 7 year of Computer life including college + work I always ran away from animations and coloring.  Last day, I was making a button and it took me pretty much time to finish it off. But, I find a good observation from it. A simple and quick way to color a button or giving a glossy effect. Have a look at these buttons.  If you are not a grahics designer, then you probably like these buttons. These buttons has been made with very simple effort, just a small work of Linear Gradient. But the fight is which color to put in Linear Gradient. So, here is my observation, you need to put the color which are close to each other and can be easily merged with each other. Like .. hmm : LIGHTBLUE, DARKBLUE, LIGHTBLUE.(3rd button) This is actually the best pattern.  2nd button is also the result of same : LIGHTGREEN, DARKGREEN, LIGHTGREEN. So, check more with this simple code : Stage {    title: "Some Cool Buttons"    width: 250    height: 280    scene: Scene {        fill:Color.BLACK        content: [            Rectangle {                x: 10,                y: 10                width: 90,                height: 30                fill: LinearGradient {                    startX: 0.0                    startY: 0.0                    endX: 0.0                    endY: 1.0                    proportional: true                    stops: [                        //   Stop { offset: 0.0 color: Color.BLACK },                      Stop {                            offset: 0.0                        color: Color.LIGHTGREEN },                        Stop {                            offset: 0.5                        color: Color.DARKGREEN },                        Stop {                            offset: 1.0                        color: Color.LIGHTGREEN }                    ]                }                opacity:0.6                arcHeight:5                arcWidth:5            },            Text {                font: Font {                size: 12                name: "Arial Bold"                letterSpacing: 0.15            }                fill:Color.WHITE                x: 18,                y: 30                content: "HelloWorld"            } ] } Some of my fav. combinations(2 already mentioned) : 1. Stop {                            offset: 0.0                        color: Color.LIME },                        Stop {                            offset: 0.5                        color: Color.DARKGREEN },                        Stop {                            offset: 1.0                        color: Color.LIME } This will look awesome, if you are writing a flashy application. Very vibrant in color. 2.  Stop {                                offset: 0.0                            color: Color.ALICEBLUE },                            Stop {                                offset: 0.5                            color: Color.BLUE },                            Stop {                                offset: 1.0                            color: Color.ALICEBLUE } 3. Stop {                                offset: 0.0                            color: Color.ORANGE },                            Stop {                                offset: 0.5                            color: Color.RED },                            Stop {                                offset: 1.0                            color: Color.ORANGE } 4. A very plain and descent effect : Stop {                                offset: 0.0                            color: Color.LIGHTYELLOW },                            Stop {                                offset: 0.5                            color: Color.YELLOWGREEN },                            Stop {                                offset: 1.0                            color: Color.LIGHTYELLOW } Enough, please let me know your choice. Is there any pattern, you follow !

With me, it happens most of the time. The basic code is over and I stuck in giving a good color to a button or a text. Now a day, a good UI is as required as basic functionality. In my 7 year...

Java

JavaFX - Samples + Usages.

Ah, finally I got JNLP working on my blog, thanks to Sergey and Vikram. I am posting some of my samples with JNLP as we can use as repository for JavaFX samples :). These all are old samples but just with JNLP, so that we can run and see the effect.  1. Spring Motion : We can create n no. of instance of Spring class. Detail is here. This example deals with Motion, Gradient and Physics Equations. 2. 3D Button Effect:  This example is about PressButton and 3D shadow effect. Detail is here. Basic deals with Shadow Effect, Gradient, and Animation. 3. Glowing Stars in Sky: This example I have created with JavaFX Production Suite. So, we made a home in Photoshop and imported that in JavaFX and then star animation is written in JavaFX. Detail is here. This sample deals with JavaFX Production Suite, Animation, Timelines and Shapes. 4. Colliding Balls: This we have blogged some 4-5 days back. This is again a physics motion with a transparent window. Detail is here. Sample deals with Motion, Equation, Timelines and Gradient. Initial positions and colors are random, so can be wired at sometime + style: StageStyle.TRANSPARENT has been used, so we will not see any frame and so close button will be missing, please press Ctrl + F4 to close the application :). I guess, the good practice is to write esc. key event and call FX.exit(). 5. Image Depth support in JavaFX:  Image depth setting or in some language we call it Z-Ordering is supported in JavaFX too. Last to last blog is about that, so here is detail. This sample basically deals with toFront and toBack API of Node and Animation(nothing cool in terms of Animation :D).  6. Pendulum Motion with Gravity Controller: This is just the last blog. Detail is here. This sample deals with Motion, Gradient and Complex Equations, Binding Feature. I have changed the code little from the prev. blog. Now, it is transparent, so it will give us a better look :) Feel free to share your experience. I hope all JNLP should work, if not please let me know. Some more I will add soon, actually all these are older samples, just tried to make repoistory, so that easy to find :).

Ah, finally I got JNLP working on my blog, thanks to Sergey and Vikram. I am posting some of my samples with JNLP as we can use as repository for JavaFX samples :). These all are old samples but just...

Java

Managing Java Process from Java Code

Back to Java :). Here is a small blog on how to manage Java Process from Java itself. Long back, I had written one blog on how to list Java Processrunning on System by Java Code. But with the new features of JDK6, youcan not only see the list but can manage the other running JavaProcess. This is possible using class LocalVirtualMachine. This classhas a list of methods : connectorAddress,displayName,getAllVirtualMachines,getLocalVirtualMachine,isAttachable,isManageable,startManagementAgent,toString,vmid Here I am just showing a simple code, which will again tell you all the running Java Process. import sun.tools.jconsole.\*;import java.util.\*;public class Main {public static void main(String[] args) {Map map = LocalVirtualMachine.getAllVirtualMachines();Iterator iter = map.values().iterator();LocalVirtualMachine vm = null;while (iter.hasNext()) {vm = (LocalVirtualMachine)iter.next();System.out.println(vm.displayName());}}} A very very small code :). Note that this class is not in rt.jar so weneed to add jconsole.jar and tools.jar in the classpath section.So, for running we need to use : D:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../javac -cp "D:/Program Files/Java/jdk1.6.0_11/lib/jconsole.jar" Main.javaD:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../java -cp .;"D:/Program Files/Java/jdk1.6.0_11/libjconsole.jar";"D:Program Files/Java/jdk1.6.0_11/lib/tools.jar" Main Or we can modify classpath in Env. Variables. Right now, in my system it is displaying: Mainorg/netbeans/modules/javafx/preview/Main 1That means, this code itself and Netbeans is running as a java process. In next blog, we will try to see how to manage(not listing) other running java code from a java code. I am not able to find too much of doc from net, so things are slow :).

Back to Java :). Here is a small blog on how to manage Java Process from Java itself. Long back, I had written one blog on how to list Java Process running on System by Java Code. But with the new...

Java

Image Depth - Z Ordering 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. 

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,...

Java

Colliding Balls + JavaFX

Here is an example of one more physics system - Colliding Balls. This is one of the most common examples we find everywhere. I have written this on transparent window. And so, if we increase the width and height of the stage + width, height variable in MotionBall.fx, it will give us a feeling like FlyingSaucer which keep on running all the way on Desktop. Here it looks on top of my code :D. So, the netbeans window on back and application is running on top of it. Actually dragged out of the browser and running. Just for adding information, we can run an application from netbeans on browser by Properties -> Run -> Run in Browser. Remeber to set the size of applet correct else the application display will not full. Initially position in this application has been generated randomly + Damping motion has been applied. So, in sometime all the balls will settle down on base. These all parameters can be adjusted in the file. Ball Effect has been generated as usual by Gradient Effect. Some variable may be unused because of future plan :D. Here goes the code: MotionBall.fx : package collidingballs;import java.lang.\*;import javafx.scene.CustomNode;import javafx.scene.Group;import javafx.scene.Node;import javafx.scene.paint.\*;import javafx.scene.shape.\*;var spring : Number = 0.05;var gravity : Number = 0.05;var width : Number = 240;var height: Number = 320;var start: Number = 0;public class MotionBall extends CustomNode {    public var x: Number;    public var y: Number;    public var velocityX: Number;    public var velocityY: Number;    public var mass: Number;    public var radius: Number;    public var color: Color;    public function collision( balls: MotionBall[]) {        for(ball in balls) {            var dx : Number = ball.x - x;            var dy : Number = ball.y - y;            var distance : Number = Math.sqrt( dx \* dx + dy \* dy );            var minDist : Number = ball.radius + radius;            if( distance < minDist ) {                var angle : Number = Math.atan2( dy, dx );                var tx : Number = x + Math.cos( angle ) \* minDist;                var ty : Number = y + Math.sin( angle ) \* minDist;                var ax : Number = ( tx - ball.x ) \* spring;                var ay : Number = ( ty - ball.y ) \* spring;                velocityX -= ax;                velocityY -= ay;                ball.velocityX += ax;                ball.velocityY += ay;            }        }    }    public function move(balls: MotionBall[]) {        velocityY += gravity;        x += velocityX;        y += velocityY;        if( x + radius >= width ) {            x = width + start - radius;            velocityX \*= - 0.9;        }         if( x - radius <= start ) {            x = start + radius;            velocityX \*= -0.9;        }        if( y + radius >= height ) {            y = height - radius;            velocityY \*= -0.9;        }         if( y - radius <= 40 ) {            y = 40 + radius;            velocityY \*= -0.9;        }    }    public override function create(): Node {        return Group {            content: [                Circle {                    centerX: bind x,                     centerY: bind y,                    radius: bind radius                    fill: bind RadialGradient {                        centerX: 0.25                        centerY: 0.25                        proportional: true                        stops: [                            Stop {                                 offset: 0.0                                color: color },                            Stop {                                 offset: 1.0                                color: Color.BLACK },                        ]                    }                }            ]        };    }Main.fx : package collidingballs;import collidingballs.MotionBall;import java.util.Random;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.scene.paint.Color;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.stage.StageStyle;var balls: MotionBall[];var rnd : Random = new Random();for( i in [1..5] ) {    insert MotionBall {        x: rnd.nextInt( 240 ),        y: rnd.nextInt( 320 ),        radius: 30        color: Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))    } into balls;}// timeline for colliding ballsvar t_collide = Timeline {    repeatCount: Timeline.INDEFINITE    keyFrames: [        KeyFrame {            time: 30ms            action: function() {                for(ball in balls) {                    ball.collision(balls);                    ball.move(balls);                }            }        }    ]}t_collide.play();Stage {    title: "Collding Balls"    style: StageStyle.TRANSPARENT    width: 240    height: 320    scene: Scene {        fill: Color.TRANSPARENT        content: [            balls        ]    }}

Here is an example of one more physics system - Colliding Balls. This is one of the most common examples we find everywhere. I have written this on transparent window. And so, if we increase the width...

Java

JavaFX ToolTip - A rough idea

I tried to write a very rough Tool Tip feature. Actually in JavaFX, we can write our own cool Tool tip. But in the meantime, we need to take care of boundary conditions of Tool tip. Here how it looks :  A shadow effect. Right now its just a bad code, we will make it good in next post :D. Here it is : package tooltip;import javafx.scene.CustomNode;import javafx.scene.effect.DropShadow;import javafx.scene.Group;import javafx.scene.Node;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.scene.shape.ShapeIntersect;import javafx.scene.text.Font;import javafx.scene.text.Text;public class ToolTip extends CustomNode {    public var x: Number;    public var y: Number;    //useless - content should decide    public var width: Number = 100;    public var height: Number = 50;    //useless-Tooltip instance should be     //added dynamically     public var op: Number = 0.0;    public var content: String;    public override function create(): Node {        return Group {            content: [                ShapeIntersect {                    effect: DropShadow {                        offsetY: -5                        offsetX: -5                        color: Color.color(0.4, 0.4, 0.4)                    };                    translateX: bind x                    translateY: bind y                    opacity: bind op                    stroke: Color.GRAY                    strokeWidth: 2                    fill: Color.GREEN                    a: [                        Rectangle {                            arcHeight:10                            arcWidth:10                            x: 0                            y: 0                            width: bind width                            height: bind height                        }                        Rectangle {                            rotate: 45                            x: 40                            y: 40                            width: bind width / 5                            height: bind 2 \* height / 5                        }                    ]                },                Text {                    font: Font {                        size: 14                    }                    translateX: bind x                    translateY: bind y                    opacity: bind op                    x: 10,                    y: 12                    content: bind content                }            ]        };    }} Main Code for this example : package tooltip;import javafx.scene.Group;import javafx.scene.Scene;import javafx.stage.Stage;import tooltip.ToolTip;import javafx.scene.shape.Rectangle;import javafx.scene.paint.Color;import javafx.scene.text.Text;import javafx.scene.text.Font;import javafx.scene.input.MouseEvent;var tt = new ToolTip;var rect = Rectangle {            x: 10,            y: 10            width: 180,            height: 70            stroke: Color.WHITE            strokeWidth: 4            fill: Color.YELLOWGREEN            opacity: 0.8        };var text = Text {            font: Font {                size: 14                name: "Arial"            }            x: 14,            y: 30            content: "HelloWorld - Beginning of a \\nnew technology always say\\n          - Hello World "        };var gp = Group {    translateX: 60    translateY: 260    onMouseMoved: function( e: MouseEvent ):Void {        tt.x = rect.x + tt.width;        tt.y = rect.y - tt.height - 20;        tt.op = 0.8;        tt.content = "You can see \\n the help of \\nHelloWorld !";    }    onMouseExited: function( e: MouseEvent ):Void {        tt.op = 0.0;    }    content: [        rect, text,tt    ]}Stage {    title: "Tool-Tip"    width: 450    height: 480    scene: Scene {        fill:Color.BLACK        content:[            gp        ]    }}⁞ If you are writing a generic tool tip take care of : 1. Scene size - it should not go off screen.2. Height and Width of tool tip - Most of the tool tip has unit height but it depends on us, we can set it.

I tried to write a very rough Tool Tip feature. Actually in JavaFX, we can write our own cool Tool tip. But in the meantime, we need to take care of boundary conditions of Tool tip. Here how it looks...

Java

Designer + Developer + JavaFX

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.0Group {    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 contentinsert fxdContent into group.content; // inserts the fxd content into the groupStage {    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 contentinsert 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.

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...

Java

Playing with Color in JavaFX

JavaFX provide a rich API for playing with colors for an image or object. The best depicted in this sample but I will show you very quickly how to change the color of a car on JSlider. I have taken this nice car from Path Animation Sample and on JSlider, I will reproduce lot of Car color like this : Actually this is very small but some one who want to develop car race required lot of car colors(it can be done at runtime) Code here : package carcolors;import javafx.scene.effect.ColorAdjust;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.animation.Timeline;import javafx.animation.KeyFrame;import javafx.animation.Interpolator;import javafx.ext.swing.SwingSlider;var hue = 0;var s = SwingSlider {                minimum: -100                maximum: 100                value: hue                vertical: false            };Stage {    title: "Application title"    width: 250    height: 280    scene: Scene {        content: [            s,            ImageView {                x: 100                y: 100                image: Image {                    url: "{__DIR__}car.png"                }                effect: ColorAdjust {                    hue: bind s.value/100.0                }            },         ]    }}

JavaFX provide a rich API for playing with colors for an image or object. The best depicted in this sample but I will show you very quickly how to change the color of a car on JSlider. I have taken...

Java

3D button Effect 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"                    }                ]            }        ]    }}

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...

Java

Mobile + Desktop JavaFX !

Just want to put the attention on one important point regarding the coding in JavaFX. Everyone who is using JavaFX has to understand that this technology is supported on Mobile, Desktop and TV(tomorrow it will be). So, its important as a developer to write Generic Applications which run across the platform. In such cases you need to know how to adjust some silly things in the code, like so desktop it can be a big font whereas you need to reduce font size for mobile or same case with images.  Here is one sample code, which can show you how to do : package sample11;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.text.Text;import javafx.scene.text.Font;var mobile = FX.getProperty("javafx.me.profiles");var isMobile = (mobile != null);var s = 24;var content = "Default";if(isMobile == true) {    s = 10;    content = "Content in Mobile"}else {     s = 20;    content = "Content on Desktop"}Stage {    title: "Checking the Font"    width: 350    height: 280    scene: Scene {        content: Text {            font : bind Font {                size : s            }            x: 10, y: 30            content: bind content        }    }} Run it on Desktop and on Mobile and see the different output. (How to run on Mobile ? ---> Netbeans6.5 -> YourProject -> Right Click ->Properties -> Run -> Run as Mobile Emulator)This feature has been nicely used in this sample :  InterestingPhotos.

Just want to put the attention on one important point regarding the coding in JavaFX. Everyone who is using JavaFX has to understand that this technology is supported on Mobile, Desktop...

Java

A simple bad digital Clock

Here how to use Java code inside JavaFX and make a simple digital clock. Bad because i have not put the proper makeup :). //Clock.fx package digitalclock;import javafx.scene.\*;import javafx.scene.paint.\*;import javafx.scene.text.\*;import javafx.scene.transform.\*;import javafx.animation.\*;import javafx.scene.shape.\*;// Java Legacyimport java.util.\*;var months:String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];public class Clock extends CustomNode {   var radius = -20;    // shifting the X center    var centerX: Number = 50 ;    // shifting the Y center    var centerY: Number = 50 ;    var hours:String;    var minutes:String;    var seconds:String;    var date:String;    var month:String;    var year:String;    var combination: String;    // intializing the watch    init {        var timeline = Timeline {            repeatCount: Timeline.INDEFINITE            keyFrames : [                KeyFrame {                    time : 1s                    action: function() {                        actionOnTick();                    }                }            ]        }        timeline.play();    }    function createCalendar() {        var date = new Date();        def calendar = Calendar.getInstance();        calendar.setTime(new Date()); // fix for mobile        calendar    }    // action taken on one tick    public function actionOnTick () {        var calendar = createCalendar();        seconds = String.valueOf(calendar.get(Calendar.SECOND));        if(seconds.length()!=2)  {            seconds = "0{seconds}";        }        minutes = String.valueOf(calendar.get(Calendar.MINUTE));        if(minutes.length()!=2)  {            minutes = "0{minutes}";        }        hours = String.valueOf(calendar.get(Calendar.HOUR));         if(hours.length()!=2)  {            hours = "0{hours}";        }        date = String.valueOf(calendar.get(Calendar.DATE));        if(date.length()!=2)  {            date = "0{date}";        }        month = months[(calendar.get(Calendar.MONTH))];        year = String.valueOf((calendar.get(Calendar.YEAR)));        combination = "{hours}:{minutes}:{seconds}  {date}-{month}-{year}";    }    // overriding the method create()    public override function create(): Node {        return Group {            transforms: [                Transform.translate(centerX, centerY)            ]            content: [                Rectangle {                    x: -35, y: 2\*radius/3 - 15                    width: 120 height: 20                    fill: Color.GRAY                    opacity:0.4                    strokeWidth: 2                    stroke: Color.BLACK                    arcHeight:10                    arcWidth:10                },                Text {                    font: Font {                        size: 11                        name: "Arial"                    }                    x: -31 , y: 2 \* radius / 3                    content: bind combination                },                  ]                }        };} //Main.fxpackage digitalclock;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.text.Text;import javafx.scene.text.Font;Stage { title: "Digital Clock" width: 160 height: 100 scene: Scene { content: Clock{} }}

Here how to use Java code inside JavaFX and make a simple digital clock. Bad because i have not put the proper makeup :). //Clock.fx package digitalclock;import javafx.scene.\*;import...

Java

Image Drag with Mouse in JavaFX

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

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...

Java

Sparkling on 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

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...

Java

Java - Instruction set rather than time

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:  209525308558755875308 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:  returnpublic 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.

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...

Java

A nasty Problem - Java Code

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.

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,...

Java

Last week.. a competition code !

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 :-).

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...

Java

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

 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 !

 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...

Java

Guassian Blur Example 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. 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},                ]            },       ]    }}

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...

Java

Next BOJUG meet

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 RoadLandmarks: 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 SDKNetBeans CompatibiltyDemo, 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- SathishKumar 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 developmenttime, etc). He'll next cover interesting topics such as developing custom Tomcat components, and how the component assembly mechanismworks.

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: ht...

Java

Button Tabs with effects in JavaFX !

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

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...

Java

Motion of Ball Under Gravity - JavaFX

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 Legacyimport 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 :

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...

Java

Insertion trigger in JavaFX

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.

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...

Java

Need more than Preview Mode - JavaFX

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.

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...

Java

JavaFX, Constrain check - Next Part !

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                    };                }            },rect,            Circle {                centerX: bind circleX, centerY: bind circleY                radius: circleRadius                fill: Color.GRAY            }        ]        fill: Color.BLACK     }}timeline.start(); It combines both the code, easing part and the constaint part :-). Virual box has been made by filling the rectangle same color as of frame.  Now, you can play around with the coordinate value and check its working fine or not. Still some condition need to check like the outer box size should be bigger. Now, look at the code of Constraint.fx written in Netbeans 6.1 example :-P.

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...

Java

JavaFX and giving motion with mouse - Easing factor

When we write animation code like moving a circle or rotating a cube, we do a bad thing. We write the coordinates according to our ease and later its pain  for others to understand the code. In the code, you will see 450 - size or 200 + radius. Now, its really tough to guess what this 450 and 200. It came from direct calculation or from addition, multiplication. Sometimes, in our mind we do those mathematical calculation and we put the final value. I have mostly done in all my previous code :-D. And this is how I got the Netbeans JavaFX sample example. For getting some hand into JavaFX code, I was trying to write a constraint code, which I was inspired from NB example, Constraint.fx in the section Best Practices -> Input. And it was all pain to understand that code, because the manipulation was done like a mathematician not like a coder. Anyway, let me first finish this blog and then you can compare it yourself. Two good thing that code covers :- 1. How to do easing (there is a separate example of that as well):  Now, when we move the mouse from one position to other, we don't want our ball(say, we are moving a ball) to stick with mouse and keep on moving with mouse. We want it into a form of motion. Like from the last position of mouse to this new position of mouse, the ball slowly moves. This can be achieved by easing  : Have a look: onMouseMoved: function( e: MouseEvent ):Void {    mouseX = e.getX();     mouseY = e.getY(); Now, if we bind our X and Y(center) of circle with mouseX, mouseY, the look will come ugly :-)( a sticky look). So, we will write an integral code here: if(Math.abs(mouseX - circleX ) > 0.1 ) {   circleX = circleX + (mouseX - circleX ) \* easing;}if( Math.abs(mouseY - circleY ) > 0.1 ) {   circleY = circleY + ( mouseY - circleY ) \* easing;} We are doing something same but in a fashionable style. We are increasing the value of CircleX and CircleY in bits and pieces and the smoothness depends on the value of easing factor which we have multiplied at the end. Lets have a look to this full code how it work : package easingcheck;import javafx.application.Frame;import javafx.application.Stage;import javafx.scene.geometry.Rectangle;import javafx.scene.paint.Color;import javafx.scene.geometry.Circle;import java.lang.Math;import javafx.animation.Timeline;import javafx.animation.KeyFrame;import javafx.input.MouseEvent;var mouseX: Number;var mouseY: Number;var circleX: Number = 250;var circleY: Number = 250;var easing = 0.04;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: "MyApplication"    width: 500    height: 500    closeAction: function() { java.lang.System.exit( 0 );     }    visible: true    stage: Stage {        content: [             Rectangle {                x: 100, y: 100                width: 300, height: 300                fill: Color.BLACK                onMouseMoved: function( e: MouseEvent ):Void {                       mouseX = e.getX();                       mouseY = e.getY();                }            },            Circle {                centerX: bind circleX, centerY: bind circleY                radius: 20                fill: Color.RED            }        ]    }}timeline.start(); We can see a smooth movement of ball(if you want to see ugly look once, then bind centerX and centerY on MouseX and MouseY). Also notice that ball is not coming out of the rectangular box because the OnMouseMoved code has been written inside the box. So, it should not come out of the box. We have to constraint the ball inside the Rectangular box completely, right now half of the ball is coming out of the box. This is 25 percent of the story. We will see how to do this job, which looks easy but not so. Keeping mind of blog size, I am continue into next blog :-)

When we write animation code like moving a circle or rotating a cube, we do a bad thing. We write the coordinates according to our ease and later its pain  for others to understand the code. In the...

Java

Reflection in JavaFX - Crying baby !

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". I always scare of using cartoon character because those are Copyright Image.   And lots of guys kicked me in the last post because code size was too big, but now its Java FX and I can also show the power of scripting :-).  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 ?

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". I always scare of using cartoon character because those...

Java

Java API + Flickr API

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 :-)

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...

Java

Boat in an ocean :-) JavaFX !

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 !

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...

Java

SubType Check Optimization in Java !

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.

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...

Java

Understanding JavaFX - Small Navigation Code

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 !

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...

Java

JavaFX small Examples.

java2s.com is one of my loving sites, yes because I got all types of code on this site. And the best part it will show you different view of codes like API based, Application based and many more. Don't know how a JFileChooser works!! Just go on the site and check for the smallest code for JFileChooser. It contains code of Java, C++, .Net, JavaScript, HTML, Python... whatever language I heard of:-).  I have not seen any repository regarding JavaFX, probably because of being very new. I proposed the site owner to add JavaFX codes as well. For adding the support of JavaFX, I have started writing small JavaFX code. Small means very small.  Here are some of the codes I have written. Please have a look and feel free to use it. 1. MapNavigation_MouseEvent.fx:  It will navigate into the map. I have not yet checked the boundary condition. Simple 14-15 line of code. 2. CarAcrossRoad.fx: Running car across road with easeboth style. This is different from linear motion. This motion smooth the object at the end. Have a look ! Some 10-11 lines of code. 3. PolygonInsideFrame.fx: Shapes are easy to make in JavaFX. I have just made one polygon(Octagone) inside a frame. Actually, I wanted to make the STOP symbol of traffic light.  4. RotatingImage.fx: Rotation of Image or any transformation is very easy in JavaFX. This example depicts a normal image rotation. 5. MoreComponentsInFrame.fx: This example will show how to add components like Button, CheckBox, RadionButton and many more inside Frame of JavaFX. 6. FullScreenExample.fx: How to run a application in full screen. There is a feature of making undecorated value : true which remove the frame border,close button in the application. It can give you a feeling like the start up screen of Netbeans. This example is for full screen but we can manage the frame size anytime. It gives you a nice look for startup. I have used the same in first navigation example. All these examples are very trivial but I guess can help for someone who is getting started with JavaFX like me.

java2s.com is one of my loving sites, yes because I got all types of code on this site. And the best part it will show you different view of codes like API based, Application based and many more....

Oracle

Integrated Cloud Applications & Platform Services