Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/cache.php on line 99

Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/query.php on line 21

Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/theme.php on line 576
Java | w3hJava

w3hJava

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


Published January 4th, 2009

JavaFX and Java Community for orkut users.

For JavaFX enthusiastic developer and designers, I have created one Orkut community, please feel free to share your experience or problem.

Here is the link for “JavaFX Developers And Designers”

For Java, I already have a 4-5 year old community. Feel free to discuss Java topics here.
I am very happy with the strength of this community now, which is around 20000. We worked continuously to remove all spams and useless topics.

Published December 26th, 2008

Handling Java Code from another Java Code

Long back, I had written one blog on how to list Java Process running on System by Java Code. But with the new features of JDK6, you can not only see the list but can manage the other running Java Process. This is possible using class LocalVirtualMachine. This class has 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 we need to add jconsole.jar and tools.jar in the classpath section.
So, here how you can run this code :

D:Program FilesJavajdk1.6.0_11binControlJavaApp>..javac -cp "D:Program Fi
lesJavajdk1.6.0_11libjconsole.jar" Main.java

D:Program FilesJavajdk1.6.0_11binControlJavaApp>..java -cp .;"D:Program F
ilesJavajdk1.6.0_11libjconsole.jar";"D:Program FilesJavajdk1.6.0_11libt
ools.jar" Main

Right now, in my system it is displaying:

Main
org/netbeans/modules/javafx/preview/Main 1

which mean this code itself and netbeans code.

In next blog, I will try to show how to manage other running java code from a java code.

Published December 8th, 2008

Glass shining demo in JavaFX..

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;

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

Published November 20th, 2008

Java Market Trend

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

1. Median Salary :

Generated By: OdinJobs - Techonology Job Search Engine

2. Jobs Trend line

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

3. Salary Histogram :

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

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

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

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

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

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

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

For more visit this link : Java Market Stats

Published September 15th, 2008

Solve 2+2 = 4

Last week, In code war, we got a problem statement in a programming contest:

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

}
}

Published September 1st, 2008

File Read Only in JDK6

This is a good feature for all those developer who do a lot of file reading, writing stuff. Java SE 6.0 gives us the feature to set file read only. There are lot of place where its correct and valid to set file as read only rather than leaving it read-write. Like you are writing some version repository or some file that should not be changed.

Here is a small code to change the file read mode:

import java.io.File;
import java.io.IOException;

public class FileReadOnly {

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

File file = new File(”test.txt”);

file.createNewFile();
System.out.println(”Before. canWrite?” + file.canWrite());

file.setWritable(false);
System.out.println(”After. canWrite?” + file.canWrite());
}
}

So, from next time don’t forget to use this.

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.