w3hJava

What, Why, When and How of Java, JavaFX and related technologies


Published August 22nd, 2008

Gradient in Java FX - Shading and 3D effect !

One thing that makes life very easy in JavaFX is the effect of Gradient. There are two types of Gradient support in JavaFX - Linear and Radial.

Linear Gradient is good for shading like

So, you can see the gradient of Black and Red on ball.  Why 2 circle because in this code, I want to show you how to achieve same effect from proportional coordinate and from absolute coordinate :-). Here is the code:

package gradientexample;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.paint.*;
import javafx.scene.geometry.Circle;

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

stage: Stage {
content: [

Circle {
centerX: 100, centerY: 100
radius: 40
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 }
]
}
},

Circle {
centerX: 200, centerY: 200
radius: 40
fill: LinearGradient {
startX:   160.0
startY:   0.0
endX: 240.0
endY: 0.0
proportional: false
stops: [
Stop { offset: 0.0 color: Color.BLACK },
Stop { offset: 1.0 color: Color.RED }
]
}
}

]
}
}

Now, Have a look of Radial Gradient, this can be used to generate 3D effect on a ball like :

Here is the code for 3D ball generator. Just click on the button on the top and it will keep on generating the random color, select the good for your application and just put it :)

Here goes the code:

package gradientexample;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.paint.*;
import javafx.scene.geometry.Circle;
import javafx.ext.swing.Button;
import java.util.Random;
import javafx.ext.swing.ComponentView;
import  javafx.scene.effect.*;

var color: Color = Color.RED;

var rnd : Random = new Random();

var button = Button {
text: "3D Ball Generator"
action: function() {
color = Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))
}
}
Frame {
title: "3D Ball Generator"
width: 700
height: 700
closeAction: function() { java.lang.System.exit( 0 );
}
visible: true

stage: Stage {
fill: Color.GRAY
content: [
Circle {
centerX: 200, centerY: 200
radius: 70
fill: bind RadialGradient {
centerX: 170
centerY: 170
radius: 100
proportional: false
stops: [
Stop { offset: 0.0 color: Color.WHITE },
Stop { offset: 1.0 color: color },
]
}
effect: GaussianBlur   {
radius: 70
input: Flood {
paint: Color.BLACK
}
}
opacity: 0.6
},
ComponentView {
component: button
}

]
}
}

Lot of good examples on these gradient are available on net.

Published August 13th, 2008

Java + PDF !

Java is such a big language now, that we ofter need to handle all type of application with Java. You may end up with a situation where you want to call MS word from Java, or Open Document from Java. Now, months back, I got a situation where I need to call some PDF formats from Java and need to do some operation on its pages. At that time, I have explored the Project - PDF Renderer on java.net site. Its an awesome project and cool operations.

A complete viewer and render. API’s are strong and I have just check this code from site itself. This code put the first page of your PDF file inside PagePanel. No doubt PDF is one of the open format used worldwide across all OS. In such a case, support from Java is something like adding more flavor in sweet.

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PagePanel;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;

/**
 * An example of using the PagePanel class to show PDFs. For more advanced
 * usage including navigation and zooming, look ad the
 * com.sun.pdfview.PDFViewer class.
 *
 * -AT-author joshua.marinacci@sun-DOT-com
 */
public class Main {

    public static void setup() throws IOException {

        //set up the frame and panel
        JFrame frame = new JFrame("PDF Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        PagePanel panel = new PagePanel();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

        //load a pdf from a byte buffer
        File file = new File("Amityform.pdf");
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
            0, channel.size());
        PDFFile pdffile = new PDFFile(buf);

        // show the first page
        PDFPage page = pdffile.getPage(0);
        panel.showPage(page);

    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {?
                    Main.setup();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}

Just download the jar file from project site. And then :

javac -cp PDFRenderer.jar Main.java

java -cp PDFRenderer.jar;. Main

It is pretty fast as well, because IO operation has been done by NIO and channels are superb.  Thanks guys for making such a great project.

Published August 7th, 2008

Binding Swing component in JavaFX

Just an small example of putting Swing code in JavaFX and binding it as well. Here I am binding the Swing Component Slider with ImageView. The opacity of Image will change according to the slider value.  Here is the code :

package newapplication;

import javafx.application.*;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.ext.swing.*;

var slide = Slider {
    minimum: 0
    maximum: 100
    value: 0
}
Frame {
    title: "JavaFX Code", width: 600, height: 600, visible: true

    stage: Stage {
        content: [
            ImageView {
                image: Image {
                    url: "http://gretawire.files.wordpress.com/2007/10/baby1.jpg"
                }
                opacity: bind (slide.value) / 100.0
            },
            ComponentView {
                component: slide
                translateX: 200
                translateY: 530
            }
        ]
    }
}

Now here we can see the opacity movement with the slider component movement.

Published July 29th, 2008

Use default client for mailing - JDK6

Sending mails or messaging from Java is never been a tough process but still most of us has to write Java Messaging API or Java Mail API to do this, which is a cumbersome process in itself.

JDK6 came with a new Desktop class in which you can give user the option to work on the default mail client, do whatever you want to do and after closing the default client the control will go back to the java code. Here is a small code to do that:

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;

public class DefaultMail {
public static void main(String[] a)throws Exception {
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

desktop.mail(”mailto”, “vaibhav.choudhary@sun.com”, null);
}
}

The idea is clean I guess, the default client will give more option than Java mail API or anything else. Desktop class give lot more other functionality as well, which we will discuss later.

Published July 11th, 2008

JavaFX and corresponding Java code

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

import javafx.ui.*;

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

and the corresponding Java Code:

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

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

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

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

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

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

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

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

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

Published June 28th, 2008

BOJUG Talk and Presentation

Last Friday, I have given a talk on Java SE 6u10 features in BOJUG meet. Here is the presentation.

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

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

-> Kernel JRE. Download small JRE.

-> Nimbus Look And Feel

-> New Applet feature which we talk in prev. blog.

And many more.

Please provide your comment on the presentation.

Published June 21st, 2008

How to use JDK 6 to solve memory issues?

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

import java.io.File;

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

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

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

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

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

Published June 15th, 2008

String goes StringBuffer

Let me first tell you what is StringBuilder. StringBuilder is a class analogous to StringBuffer added in JDK 1.5. This class is designed to use in place where StringBuffer is used by single thread(like in most
of the cases). According to documentation, StringBuilder should work faster than StringBuffer. So ” thread unsafe, fast”.

I was reading one of the posts of orkut Java community asking “what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer”. Valid question ! GC need to work little more in case of String, but thats fair.

No don’t use String class for concatenation operation, always use StringBuffer / StringBuilder and let me tell you why ?

This is a simple Java code for string addition in String and StringBuffer:

class StringTest {
    public static void main(String[] args)
   {
       String s = “just a string”;
       s = s + “add me too”;
       System.out.println(s);
       /*
       StringBuffer s = new StringBuffer(”just a string”);
      //StringBuilder s = new StringBuilder(”just a string”);
      s = s.append(”add me too”);
      System.out.println(s);
      */
     }
}

Alright, now have a look on the bytecode of this program.

>> javac StringTest.java
>> javap -c StringTest

Compiled from “StringTest.java”
class StringTest extends java.lang.Object{
StringTest();
Code:
0:   aload_0
1:   invokespecial   #1; //Method java/lang/Object.“:()V
4:   return

public static void main(java.lang.String[]);
Code:
0:   ldc     #2; //String just a string
2:   astore_1
3:   new     #3; //class java/lang/StringBuilder
6:   dup
7:   invokespecial   #4; //Method java/lang/StringBuilder.“:()V
10:  aload_1
 11:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
14:  ldc     #6; //String add me too
16:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)
Ljava/lang/StringBuilder;
19:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22:  astore_1
23:  getstatic       #8; //Field java/lang/System.out:Ljava/io/PrintStream;
26:  aload_1
27:  invokevirtual   #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
30:  return
}

Just see line no. 11. Interesting, the plus sign we used for addition is not as innocent as it looks. String itself use StringBuffer(StringBuilder) to add two strings and hence taking much more time than normal append operation done by StringBuffer. Let me give you more evidence, run verbose option and check the time

>> javac -verbose StringTest.java

and check the other one, that is, with StringBuffer one.

You can clearly figure out the time difference and make a try with StringBuilder, time should reduce furthermore.

Published June 9th, 2008

How Java handles overriding

One of the blog readers recently asked a question about “How Java handles overriding !”  So, I decided to make one entry for the answer.

Yes overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++. In C++, the concept of overriding functions are handled by Virtual Table, VTable(This wiki link contains lot of information). Whereas in Java there is some other concept. Before going into the depth, let’s see some of the basic things which one should need to know before making their hands dirty in overriding concept.

Here is a Simple HelloWorld Program:

class Hello {
public static void main(String[] args)
{
System.out.println(”Hello Bloggers!”);
}
}

Lets see what the bytecode is generating, javap -c Hello(more about javap)

Compiled from "Hello.java"
class Hello extends java.lang.Object{
Hello();
Code:
0:   aload_0
1:   invokespecial   #1; //Method java/lang/Object."":()V
4:   return

public static void main(java.lang.String[]);
Code:
0:   new     #2; //class Hello
3:   dup
4:   invokespecial   #3; //Method “”:()V
7:   astore_1
8:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
11:  ldc     #5; //String Hello it is
13:  invokevirtual   #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V
16:  return

}

Have a look on these lines:

1:   invokespecial   #1; //Method java/lang/Object."":()V
4:   invokespecial   #3; //Method "":()V
13: invokevirtual   #6; //Method java/io/PrintStream.println:(Ljava/lang/Str
ing;)V

These are the lines related to method invocation. So what the heck is this invokespecial and invokevirtual ? Actually JVM used 4 different kinds of instructions for method invocation those are :

- invokevirtual - This is for instance method like System.out.println(”Hello Bloggers!”) here.
- invokestatic - This is for class methods.
- invokespecial - This is for special things. It is used when
- call , instance initialization.
- super call, when you will call something from super.method
- private methods. As private methods can’t be overridden so we need to put this in a special category.
- invokeinterface - invoking instance method with interface reference(Soon we will see the example)

Now we are very clear that why invokespecial has been used at #1 and #3 whereas invokevirtual at #6. Ok, lets write some code which can see the usages of all four.

interface interfaceForHello {
public void noUse();
}

class Hello implements interfaceForHello {
public void noUse() {
System.out.println("No use");
}
public static void staticMethod()
{
System.out.println("Static method");
}
public static void main(String[] args)
{
interfaceForHello iface = new Hello();
iface.noUse();
Hello.staticMethod();
System.out.println(”Hello Bloggers !  “);
}
}

And here goes the javap -a Hello:

Compiled from "Hello.java"
class Hello extends java.lang.Object implements interfaceForHello{
Hello();
Code:
0:    aload_0
1:    invokespecial    #1; //Method java/lang/Object."":()V
4:    return

public void noUse();
Code:
0:    getstatic    #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3:    ldc    #3; //String No use
5:    invokevirtual    #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8:    return

public static void staticMethod();
Code:
0:    getstatic    #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3:    ldc    #5; //String Static method
5:    invokevirtual    #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8:    return

public static void main(java.lang.String[]);
Code:
0:    new    #6; //class Hello
3:    dup
4:    invokespecial    #7; //Method “”:()V
7:    astore_1
8:    aload_1
9:    invokeinterface    #8,  1; //InterfaceMethod interfaceForHello.noUse:()V
14:    invokestatic    #9; //Method staticMethod:()V
17:    getstatic    #2; //Field java/lang/System.out:Ljava/io/PrintStream;
20:    ldc    #10; //String Hello Bloggers !
22:    invokevirtual    #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25:    return

}

Published May 28th, 2008

Multi-threading in Java

One of the greatest features in Java is support for multi-threading. Generally we have misconceptions about the concepts of threading. We tend to think it more as a part of coding and hence take it only at coding time. Threading is all about designing and not about coding. If you want to write a good threading code, think of it before writing the code. Sometime back, I had made a presentation on multi-threading in Java with some demos. Have a look here :)

here

Presentation is very basic and talk simple things. Your comments are most welcome.