Monday, December 28, 2015

Files.lines() read text file returned by JavaFX FileChooser

Example show how to read all lines from a file returned by JavaFX FileChooser, using Files.lines().


package javafxreadtextfile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXReadTextFile extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);

        VBox rootBox = new VBox();
        rootBox.getChildren().add(btnLoad);
         
        Scene scene = new Scene(rootBox, 300, 300);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = (ActionEvent event) -> {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters()
            .addAll(
                new FileChooser.ExtensionFilter("TXT files (*.TXT)", "*.TXT"),
                new FileChooser.ExtensionFilter("txt files (*.txt)", "*.txt"));
        
        File file = fileChooser.showOpenDialog(null);
        if (file != null) {
            try {
                Files.lines(file.toPath()).forEach(System.out::println);
            } catch (IOException ex) {
                Logger.getLogger(JavaFXReadTextFile.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    };

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


Sunday, December 6, 2015

JavaFX FileChooser to open image file, and display on ImageView, run on Ubuntu GNOME 15.10/NetBeans 8.1

Re-test "Use JavaFX FileChooser to open image file, and display on ImageView" on Ubuntu GNOME 15.10/NetBeans 8.1.



package javafxpixel;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFxPixel extends Application {
    
    ImageView myImageView;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button("Load");
        btnLoad.setOnAction(btnLoadEventListener);
         
        myImageView = new ImageView();        
         
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, myImageView);
         
        Scene scene = new Scene(rootBox, 300, 300);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
 
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
             
            //Set extension filter
            FileChooser.ExtensionFilter extFilterJPG = 
                    new FileChooser.ExtensionFilter("JPG files (*.JPG)", "*.JPG");
            FileChooser.ExtensionFilter extFilterjpg = 
                    new FileChooser.ExtensionFilter("jpg files (*.jpg)", "*.jpg");
            FileChooser.ExtensionFilter extFilterPNG = 
                    new FileChooser.ExtensionFilter("PNG files (*.PNG)", "*.PNG");
            FileChooser.ExtensionFilter extFilterpng = 
                    new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
            fileChooser.getExtensionFilters()
                    .addAll(extFilterJPG, extFilterjpg, extFilterPNG, extFilterpng);

            //Show open file dialog
            File file = fileChooser.showOpenDialog(null);
            
            try {
                BufferedImage bufferedImage = ImageIO.read(file);
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);
                myImageView.setImage(image);
            } catch (IOException ex) {
                Logger.getLogger(JavaFxPixel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
}

Wednesday, November 11, 2015

Query InterNIC server's whois

Last example show Java example using WhoisClient class to query whois. Alternatively, we can query InterNIC server's whois without WhoisClient class.


package javawhois;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoIs {
    
    private final static String WHO ="google.com";

    private final static String WHOIS_HOST = "whois.internic.net";
    private final static int WHOIS_PORT = 43;

    public static void main(String[] args) {
        int c;
        Socket socket = null; 

        String query = "=" + WHO + "\r\n";
        byte buf[] = query.getBytes();
        
        try {
            socket = new Socket(WHOIS_HOST, WHOIS_PORT);
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream(); 

            out.write(buf); 
            out.flush();
            while ((c = in.read()) != -1) { 
                System.out.print((char) c); 
            } 
            System.out.print("\nDone\n");
        } catch (IOException ex) {
            Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
            System.out.print(ex.getMessage());
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}


Sunday, November 8, 2015

Java example using WhoisClient class

The WhoisClient class implements the client side of the Internet Whois Protocol defined in RFC 954. To query a host you create a WhoisClient instance, connect to the host, query the host, and finally disconnect from the host. If the whois service you want to query is on a non-standard port, connect to the host at that port.
org.apache.commons.net.whois.WhoisClient

Example:
package javawhoisclient;

import java.io.IOException;
import org.apache.commons.net.whois.WhoisClient;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoisClient {

    public static void main(String[] args) {
        WhoisClient whois;

        whois = new WhoisClient();

        try {
            whois.connect(WhoisClient.DEFAULT_HOST);
            System.out.println(whois.query("=google.com"));
            whois.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            return;
        }
    }

}




To use WhoisClient class in your program, you have to include library commons-net-3.3 in your code, it can be download here: https://commons.apache.org/proper/commons-net/index.html

This video show how to download and add library commons-net-3.3 to NetBeans IDE.


Next:
query InterNIC server's whois without WhoisClient class.

Install Netbeans 8.1 0n Ubuntu 15.10

Netbeans IDE 8.1 just released.

This video show how to download and install Netbeans IDE 8.1 on Ubuntu-GNOME 15.10


To install Ubuntu 8.1 on Ubuntu:
- Visit https://netbeans.org/ to download installer-file.
- chmod +x <installer-file-name>.
- run it with command:
./<installer-file-name> to run the installer.

The only special is to select correct path to JDK, 1:40 in the above video.

My JDK was installed with ppa:webupd8team, it's on "/usr/lib/jvm/java-8-oracle".




If you missed the setting JDK path, you still run edit netbeans.conf, to specify netbeans_jdkhome, or run netbeans with --jdkhome option. (ref: http://wiki.netbeans.org/FaqRunningOnJre)

netbeans.conf to set netbeans_jdkhome:



run netbeans with --jdkhome option:


Java I/O, NIO and NIO.2


Java I/O, NIO and NIO.2

Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes and related types, and the reader/writer classes). Next, you'll learn about NIO's buffer, channel, selector, regular expression, charset, and formatter APIs. Finally, you'll discover NIO.2's offerings in terms of an improved file system interface, asynchronous I/O, and the completion of socket channel functionality.

After reading and using thi book, you'll gain the accelerated knowledge and skill level to really build applications with efficient data access, especially for today's cloud computing streaming data needs.

What you’ll learn
  • How to set permissions and more with the classic File class
  • How to build a flat file database with RandomAccessFile
  • Get to know the byte array, file, filter, and other kinds of streams
  • Master serialization and externalization
  • Discover character streams and their associated writers/readers
  • Tour the buffer APIs
  • Work with channels to transfer buffers to and from I/O services
  • Find out about selectors and readiness selection
  • Master regular expressions
  • Discover charsets and their association with Java's String< class
  • Take advantage of the formatter API to create formatted output
  • How to customize the formatter API
  • Explore the improved file system interface
  • Discover asynchronous I/O and its association with futures and completion handlers
  • Encounter socket channel improvements, including multicasting
Who this book is for
This book is for those experienced with Java, beyond the fundamentals.

Table of Contents
Part 1: Getting Started with I/O
Chapter 1: I/O Basics and APIs
Part 2: Classic I/O APIs
Chapter 2: File
Chapter 3: RandomAccessFile
Chapter 4: Streams
Chapter 5: Writers and Readers
Part 3: New I/O APIs
Chapter 6: Buffers
Chapter 7: Channels
Chapter 8: Selectors
Chapter 9: Regular Expressions
Chapter 10: Charsets
Chapter 11: Formatter and Scanner
Part 4: More New I/O APIs
Chapter 12: File System APIs
Chapter 13: Asynchronous I/O
Chapter 14: Additional NIO.2 APIs
Appendix A: Answers to Review Exercises

Thursday, October 29, 2015

Install java-gnome on Ubuntu 15.10, and first try.

The java-gnome User Interface Library is a Java bindings for GTK and GNOME. To install it on Ubuntu, enter the command in Terminal:
$ sudo apt-get install libjava-gnome-java


(reference: http://java-gnome.sourceforge.net/get/ubuntu.php)

First try:



Create a my first example ExamplePressMe.java (copt from HERE), under trial directory ~/java-gnome-works.
/*
 * ExamplePressMe.java
 *
 * Copyright (c) 2006-2008 Operational Dynamics Consulting Pty Ltd
 *
 * The code in this file, and the library it is a part of, are made available
 * to you by the authors under the terms of the "GNU General Public Licence,
 * version 2" See the LICENCE file for the terms governing usage and
 * redistribution.
 */
package button;

import org.gnome.gdk.Event;
import org.gnome.gtk.Button;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Label;
import org.gnome.gtk.VBox;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;

/**
 * A simple Window with a Label and a Button in it. Demonstrates the basics of
 * initializing GTK, packing Widgets into Containers, and hooking up signals.
 * 
 * This example has been around, in one form or another, since the very
 * beginnings of java-gnome. If you're just starting out with GTK and GNOME
 * don't worry; we started here too.
 * 
 * @author Andrew Cowie
 * @since 4.0.0
 */
public class ExamplePressMe
{
    public static void main(String[] args) {
        final Window w;
        final VBox x;
        final Label l;
        final Button b;

        /*
         * Initialize GTK. You MUST call this to load the library before
         * trying to use any other elements provided by java-gnome.
         */

        Gtk.init(args);

        /*
         * Create a top level Window. It's the Container around which the
         * window manager draws decorations such as a title bar, minimize and
         * close buttons, resize edges, etc.
         */

        w = new Window();

        /*
         * Since a Window is a Bin, it can only have one child Widget. That's
         * probably not very useful in most cases. To take that one slot and
         * turn it into many, we use a VBox, a Container that will stack its
         * children vertically.
         */

        x = new VBox(false, 3);

        /*
         * Create a Label with some text describing the Button that will
         * follow, then add it to the VBox.
         */

        l = new Label("Go ahead:\nMake my day");
        x.add(l);

        /*
         * Create our Button, with a nice explicit bit of text labelling it
         * and what you're to do.
         */

        b = new Button("Press me!");
        x.add(b);

        /*
         * Now the magic part. Just sitting there, the Button won't do
         * anything. You need to hook up a "signal handler" to deal with the
         * 'clicked' signal. This is how we do it in java-gnome.
         * 
         * Button.Clicked is a Java interface. You create an instance of it to
         * do what you want when the callback happens, and then pass it to the
         * Button's connect() method.
         * 
         * The onClicked() method is what is required by the Button.Clicked
         * interface. Most IDEs will prompt you asking if you want to "Add
         * unimplemented methods?" You bet! And ta-da! You have exactly the
         * signature you need to implement a 'clicked' signal handler.
         * 
         * Since we declared b as final we can use it in the anonymous nested
         * class (yet *another* reason that final is worth using). If the
         * situation were otherwise, then the source parameter can be used to
         * find out what Button was clicked.
         */

        b.connect(new Button.Clicked() {
            public void onClicked(Button source) {
                System.out.println("I was clicked: " + b.getLabel());
            }
        });

        /*
         * Now we pack the VBox into our Window, set the Window's title, and
         * invoke the command to realize everything onto the screen.
         */

        w.add(x);
        w.setTitle("Hello World");
        w.showAll();

        /*
         * We would be be done except for one last detail. Closing a Window
         * does not terminate the application. If that's what you want (and we
         * do indeed want that here) then you need to hook up a handler to do
         * something when the 'delete-event' signal is emitted.
         * 
         * Again, the method here implements the interface.
         */

        w.connect(new Window.DeleteEvent() {
            public boolean onDeleteEvent(Widget source, Event event) {
                Gtk.mainQuit();
                return false;
            }
        });

        /*
         * Now we're ready to run the main loop. The signals we've hooked up
         * handlers for above won't be emitted until the user does something,
         * but no events will be processed until the main loop is running;
         * that's where the signals will come from. This call blocks. You have
         * finished setting things up and now it's up to your signal handlers
         * to carry out the program's logic in response to the user's actions;
         * the essence of event-driven programming.
         */

        Gtk.main();
    }
}


Make a tests directory to hold the output.

Enter the command to compile the java code with java-gnome.
$ javac -classpath /usr/share/java/gtk-4.1.jar -d tests ExamplePressMe.java

Run it:
$ java -classpath /usr/share/java/gtk-4.1.jar:tests button.ExamplePressMe

Where /usr/share/java/gtk-4.1.jar is the installed gtk-4.1.jar.


(reference: http://java-gnome.sourceforge.net/README.html)

Install Netbeans IDE on Ubuntu GNOME 15.10

Before install Netbeans IDE, install JDK8 first.

Follow the video to install Netbeans IDE on Ubuntu GNOME 15.10:



Try a example in Netbeans IDE:

Install Oracle Java 8 on Ubuntu 15.10 via ppa:webupd8team


ppa:webupd8team/java is a Oracle Java (JDK) Installer (automatically downloads and installs Oracle JDK7/JDK8/JDK9).

To install on Ubuntu 15.10, enter the commands in terminal:
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer


webupd8team/java also provide oracle-java8-set-default, automatically sets the Java 8 environment variables and sets JDK8 as the default JDK. To install it, use the following command:
$ sudo apt-get install oracle-java8-set-default




Monday, October 5, 2015

Remote run JavaFX on Raspbian Jessie, from Netbeans/Windows 10

Raspbian Jessie is a new major upgrade of official Raspberry Pi OS. This video show how to create Remote Java SE Platform on Netbeans IDE running under Windows 10, deploy JavaFX application remotely to Raspberry Pi running Raspbian Jessie.


Source: Remote run JavaFX on Raspbian Jessie, from Netbeans/Windows 10

Friday, September 25, 2015

JavaFX Lighting effect of Light.Spot


javafx.scene.effect.Light.Spot represents a spot light source at a given position in 3D space, with configurable direction and focus.


package javafx_lighting;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Lighting extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        //Light.Spot: Represents a spot light source at a given position in 
        //3D space, with configurable direction and focus.
        Light.Spot lightSpot = new Light.Spot();
        lightSpot.setX(0);
        lightSpot.setY(0);
        lightSpot.setZ(0);
        lightSpot.setColor(Color.ANTIQUEWHITE);
        Lighting lighting = new Lighting();
        lighting.setLight(lightSpot);
        lighting.setSurfaceScale(5.0);
        lighting.setDiffuseConstant(1.0);
        
        ColorPicker colorPicker = new ColorPicker(Color.ANTIQUEWHITE);
        colorPicker.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                lightSpot.setColor(colorPicker.getValue());
            }
        });
 
        Button btn = new Button("Button with Lighting");
        btn.setEffect(lighting);

        TextField textField = new TextField("TextField with Lighting");
        textField.setEffect(lighting);
        
        Text text = new Text("Text with lighting");
        text.setFont(Font.font ("Verdana", FontWeight.BOLD, 40));
        text.setFill(Color.WHITE);
        text.setEffect(lighting);

        Circle circle = new Circle(20,Color.WHITE);
        circle.setEffect(lighting);

        Rectangle rectangle = new Rectangle(50, 50, Color.WHITE);
        rectangle.setEffect(lighting);
        
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));
        imageView.setEffect(lighting);
        
        HBox hBoxShape = new HBox();
        hBoxShape.getChildren().addAll(rectangle, circle, imageView);

        Label labelXYZ = new Label("X, Y, Z");
        Slider sliderX = new Slider();
        sliderX.setMin(0);
        sliderX.setMax(900.0);
        sliderX.setValue(0);
        sliderX.setMajorTickUnit(100);
        sliderX.setMinorTickCount(2);
        sliderX.setShowTickLabels(true);
        sliderX.setShowTickMarks(true);
        sliderX.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setX((Double)new_val);
        });

        Slider sliderY = new Slider();
        sliderY.setMin(0);
        sliderY.setMax(500.0);
        sliderY.setValue(0);
        sliderY.setMajorTickUnit(100);
        sliderY.setMinorTickCount(2);
        sliderY.setShowTickLabels(true);
        sliderY.setShowTickMarks(true);
        sliderY.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setY((Double)new_val);
        });

        Slider sliderZ = new Slider();
        sliderZ.setMin(0);
        sliderZ.setMax(500.0);
        sliderZ.setValue(0);
        sliderZ.setMajorTickUnit(100);
        sliderZ.setMinorTickCount(2);
        sliderZ.setShowTickLabels(true);
        sliderZ.setShowTickMarks(true);
        sliderZ.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setZ((Double)new_val);
        });
        
        //
        Label labelPointsAtX = new Label("PointsAtX, PointsAtY, PointsAtZ");
        
        Slider sliderPointsAtX = new Slider();
        sliderPointsAtX.setMin(0);
        sliderPointsAtX.setMax(900.0);
        sliderPointsAtX.setValue(0);
        sliderPointsAtX.setMajorTickUnit(300);
        sliderPointsAtX.setMinorTickCount(3);
        sliderPointsAtX.setShowTickLabels(true);
        sliderPointsAtX.setShowTickMarks(true);
        sliderPointsAtX.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setPointsAtX((Double)new_val);
        });
        
        Slider sliderPointsAtY = new Slider();
        sliderPointsAtY.setMin(0);
        sliderPointsAtY.setMax(500.0);
        sliderPointsAtY.setValue(0);
        sliderPointsAtY.setMajorTickUnit(100);
        sliderPointsAtY.setMinorTickCount(2);
        sliderPointsAtY.setShowTickLabels(true);
        sliderPointsAtY.setShowTickMarks(true);
        sliderPointsAtY.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setPointsAtY((Double)new_val);
        });
        
        Slider sliderPointsAtZ = new Slider();
        sliderPointsAtZ.setMin(0);
        sliderPointsAtZ.setMax(500.0);
        sliderPointsAtZ.setValue(0);
        sliderPointsAtZ.setMajorTickUnit(100);
        sliderPointsAtZ.setMinorTickCount(2);
        sliderPointsAtZ.setShowTickLabels(true);
        sliderPointsAtZ.setShowTickMarks(true);
        sliderPointsAtZ.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightSpot.setPointsAtZ((Double)new_val);
        });

        //
        
        Label labelSurfaceScale = new Label("SurfaceScale");
        Slider sliderSurfaceScale = new Slider();
        sliderSurfaceScale.setMin(0);
        sliderSurfaceScale.setMax(10);
        sliderSurfaceScale.setValue(5.0);
        sliderSurfaceScale.setMajorTickUnit(1);
        sliderSurfaceScale.setMinorTickCount(2);
        sliderSurfaceScale.setShowTickLabels(true);
        sliderSurfaceScale.setShowTickMarks(true);
        sliderSurfaceScale.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setSurfaceScale((Double)new_val);
        });

        Label labelDiffuse = new Label("DiffuseConstant");
        Slider sliderDiffuse = new Slider();
        sliderDiffuse.setMin(0);
        sliderDiffuse.setMax(2);
        sliderDiffuse.setValue(1);
        sliderDiffuse.setMajorTickUnit(1);
        sliderDiffuse.setMinorTickCount(4);
        sliderDiffuse.setShowTickLabels(true);
        sliderDiffuse.setShowTickMarks(true);
        sliderDiffuse.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setDiffuseConstant((Double)new_val);
        });
        
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.getChildren().addAll(colorPicker, btn, text, textField, hBoxShape, 
                labelXYZ, sliderX, sliderY, sliderZ,
                labelPointsAtX, sliderPointsAtX, sliderPointsAtY, sliderPointsAtZ,
                labelSurfaceScale, sliderSurfaceScale, labelDiffuse, sliderDiffuse);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 1000, 600);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

JavaFX Lighting effect of Light.Point


javafx.scene.effect.Light.Point represents a light source at a given position in 3D space.


package javafx_lighting;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Lighting extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        //Light.Point: Represents a light source at a given position in 3D space.
        Light.Point lightPoint = new Light.Point();
        lightPoint.setX(0);
        lightPoint.setY(0);
        lightPoint.setZ(0);
        lightPoint.setColor(Color.GOLD);
        Lighting lighting = new Lighting();
        lighting.setLight(lightPoint);
        lighting.setSurfaceScale(5.0);
        lighting.setDiffuseConstant(1.0);
        
        ColorPicker colorPicker = new ColorPicker(Color.GOLD);
        colorPicker.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                lightPoint.setColor(colorPicker.getValue());
            }
        });
 
        Button btn = new Button("Button with Lighting");
        btn.setEffect(lighting);

        TextField textField = new TextField("TextField with Lighting");
        textField.setEffect(lighting);
        
        Text text = new Text("Text with lighting");
        text.setFont(Font.font ("Verdana", FontWeight.BOLD, 40));
        text.setFill(Color.WHITE);
        text.setEffect(lighting);

        Circle circle = new Circle(20,Color.WHITE);
        circle.setEffect(lighting);

        Rectangle rectangle = new Rectangle(50, 50, Color.WHITE);
        rectangle.setEffect(lighting);
        
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));
        imageView.setEffect(lighting);
        
        HBox hBoxShape = new HBox();
        hBoxShape.getChildren().addAll(rectangle, circle, imageView);

        Label labelX = new Label("X: "
                + "The x coordinate of the light position.");
        Slider sliderX = new Slider();
        sliderX.setMin(0);
        sliderX.setMax(900.0);
        sliderX.setValue(0);
        sliderX.setMajorTickUnit(100);
        sliderX.setMinorTickCount(2);
        sliderX.setShowTickLabels(true);
        sliderX.setShowTickMarks(true);
        sliderX.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightPoint.setX((Double)new_val);
        });
        
        Label labelY = new Label("Y: "
                + "The y coordinate of the light position.");
        Slider sliderY = new Slider();
        sliderY.setMin(0);
        sliderY.setMax(500.0);
        sliderY.setValue(0);
        sliderY.setMajorTickUnit(100);
        sliderY.setMinorTickCount(2);
        sliderY.setShowTickLabels(true);
        sliderY.setShowTickMarks(true);
        sliderY.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightPoint.setY((Double)new_val);
        });
        
        Label labelZ = new Label("Z: "
                + "The z coordinate of the light position.");
        Slider sliderZ = new Slider();
        sliderZ.setMin(0);
        sliderZ.setMax(500.0);
        sliderZ.setValue(0);
        sliderZ.setMajorTickUnit(100);
        sliderZ.setMinorTickCount(2);
        sliderZ.setShowTickLabels(true);
        sliderZ.setShowTickMarks(true);
        sliderZ.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lightPoint.setZ((Double)new_val);
        });
        
        Label labelSurfaceScale = new Label("SurfaceScale");
        Slider sliderSurfaceScale = new Slider();
        sliderSurfaceScale.setMin(0);
        sliderSurfaceScale.setMax(10);
        sliderSurfaceScale.setValue(1.5);
        sliderSurfaceScale.setMajorTickUnit(1);
        sliderSurfaceScale.setMinorTickCount(2);
        sliderSurfaceScale.setShowTickLabels(true);
        sliderSurfaceScale.setShowTickMarks(true);
        sliderSurfaceScale.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setSurfaceScale((Double)new_val);
        });
        
        Label labelDiffuse = new Label("DiffuseConstant");
        Slider sliderDiffuse = new Slider();
        sliderDiffuse.setMin(0);
        sliderDiffuse.setMax(2);
        sliderDiffuse.setValue(1);
        sliderDiffuse.setMajorTickUnit(1);
        sliderDiffuse.setMinorTickCount(4);
        sliderDiffuse.setShowTickLabels(true);
        sliderDiffuse.setShowTickMarks(true);
        sliderDiffuse.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setDiffuseConstant((Double)new_val);
        });
        
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.getChildren().addAll(colorPicker, btn, text, textField, hBoxShape, 
                labelX, sliderX, labelY, sliderY, labelZ, sliderZ,
                labelSurfaceScale, sliderSurfaceScale, labelDiffuse, sliderDiffuse);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 900, 500);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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



Related:
- JavaFX Lighting effect of Light.Distant

Tuesday, September 22, 2015

Interactive demo of JavaFX Lighting effect of Light.Distant


JavaFX_Lighting.java
package javafx_lighting;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Lighting extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        //Light.Distant: Represents a distant light source.
        Light.Distant light = new Light.Distant();
        light.setAzimuth(45);
        light.setElevation(45);
        light.setColor(Color.AZURE);
        Lighting lighting = new Lighting();
        lighting.setLight(light);
        lighting.setSurfaceScale(5.0);
        lighting.setDiffuseConstant(1.0);
        
        ColorPicker colorPicker = new ColorPicker(Color.AZURE);
        colorPicker.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                light.setColor(colorPicker.getValue());
            }
        });
 
        Button btn = new Button("Button with Lighting");
        btn.setEffect(lighting);

        TextField textField = new TextField("TextField with Lighting");
        textField.setEffect(lighting);
        
        Text text = new Text("Text with lighting");
        text.setFont(Font.font ("Verdana", FontWeight.BOLD, 40));
        text.setFill(Color.WHITE);
        text.setEffect(lighting);

        Circle circle = new Circle(20,  Color.rgb(255,255,255));
        circle.setEffect(lighting);

        Rectangle rectangle = new Rectangle(50, 50, Color.rgb(255,255,255));
        rectangle.setEffect(lighting);
        
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));
        imageView.setEffect(lighting);
        
        HBox hBoxShape = new HBox();
        hBoxShape.getChildren().addAll(rectangle, circle, imageView);

        Label labelAzimuth = new Label("Azimuth: "
                + "the direction angle for the light source on the XY plane.");
        Slider sliderAzimuth = new Slider();
        sliderAzimuth.setMin(0);
        sliderAzimuth.setMax(360);
        sliderAzimuth.setValue(45);
        sliderAzimuth.setMajorTickUnit(90);
        sliderAzimuth.setMinorTickCount(3);
        sliderAzimuth.setShowTickLabels(true);
        sliderAzimuth.setShowTickMarks(true);
        sliderAzimuth.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            light.setAzimuth((Double)new_val);
        });
        
        Label labelElevation = new Label("Elevation: "
                + "the direction angle for the light source on the YZ plane.");
        Slider sliderElevation = new Slider();
        sliderElevation.setMin(0);
        sliderElevation.setMax(360);
        sliderElevation.setValue(45);
        sliderElevation.setMajorTickUnit(90);
        sliderElevation.setMinorTickCount(3);
        sliderElevation.setShowTickLabels(true);
        sliderElevation.setShowTickMarks(true);
        sliderElevation.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            light.setElevation((Double)new_val);
        });
        
        Label labelSurfaceScale = new Label("SurfaceScale");
        Slider sliderSurfaceScale = new Slider();
        sliderSurfaceScale.setMin(0);
        sliderSurfaceScale.setMax(10);
        sliderSurfaceScale.setValue(1.5);
        sliderSurfaceScale.setMajorTickUnit(1);
        sliderSurfaceScale.setMinorTickCount(2);
        sliderSurfaceScale.setShowTickLabels(true);
        sliderSurfaceScale.setShowTickMarks(true);
        sliderSurfaceScale.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setSurfaceScale((Double)new_val);
        });
        
        Label labelDiffuse = new Label("DiffuseConstant");
        Slider sliderDiffuse = new Slider();
        sliderDiffuse.setMin(0);
        sliderDiffuse.setMax(2);
        sliderDiffuse.setValue(1);
        sliderDiffuse.setMajorTickUnit(1);
        sliderDiffuse.setMinorTickCount(4);
        sliderDiffuse.setShowTickLabels(true);
        sliderDiffuse.setShowTickMarks(true);
        sliderDiffuse.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            lighting.setDiffuseConstant((Double)new_val);
        });
        
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.getChildren().addAll(colorPicker, btn, text, textField, hBoxShape, 
                labelAzimuth, sliderAzimuth, labelElevation, sliderElevation,
                labelSurfaceScale, sliderSurfaceScale, labelDiffuse, sliderDiffuse);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 853, 480);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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



Related:
- JavaFX Lighting effect of Light.Point

JavaFX Lighting effect


package javafx_lighting;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.effect.Lighting;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Lighting extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn1 = new Button();
        btn1.setText("Normal Button");
        Button btn2 = new Button();
        btn2.setText("Button with Lighting");
        btn2.setEffect(new Lighting());
        
        TextField textField1 = new TextField("Normal TextField");
        TextField textField2 = new TextField("TextField with Lighting");
        textField2.setEffect(new Lighting());
        
        Text text1 = new Text("Normal Text");
        text1.setFont(Font.font ("Verdana", FontWeight.BOLD, 40));
        text1.setFill(Color.RED);
        Text text2 = new Text("Text with lighting");
        text2.setFont(Font.font ("Verdana", FontWeight.BOLD, 40));
        text2.setFill(Color.RED);
        text2.setEffect(new Lighting());
        
        Circle circle1 = new Circle(20,  Color.rgb(156,216,255));
        Circle circle2 = new Circle(20,  Color.rgb(156,216,255));
        circle2.setEffect(new Lighting());
        
        Rectangle rectangle1 = new Rectangle(100, 100, Color.rgb(156,216,255));
        Rectangle rectangle2 = new Rectangle(100, 100, Color.rgb(156,216,255));
        rectangle2.setEffect(new Lighting());
        HBox hBoxShape = new HBox();
        hBoxShape.getChildren().addAll(rectangle1, rectangle2, circle1, circle2);

        ImageView imageView1 = new ImageView(new Image("http://goo.gl/kYEQl"));
        ImageView imageView2 = new ImageView(new Image("http://goo.gl/kYEQl"));
        imageView2.setEffect(new Lighting());
        HBox hBoxImageView = new HBox();
        hBoxImageView.getChildren().addAll(imageView1, imageView2);

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.getChildren().addAll(btn1, btn2, text1, text2, 
                textField1, textField2,
                hBoxShape, hBoxImageView);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 450, 400);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Thursday, September 17, 2015

JavaFX Transition Animation with Reflection effect

JavaFX example to combine Transition Animation and Reflection effect.



package javafx_transitionexample;

import javafx.animation.FadeTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.RotateTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TransitionExample extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Transition Example
        //ref: http://docs.oracle.com/javafx/2/animations/basics.htm
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));
        
        Reflection reflection = new Reflection();
        imageView.setEffect(reflection);

        FadeTransition fadeTransition
                = new FadeTransition(Duration.millis(3000), imageView);
        fadeTransition.setFromValue(1.0f);
        fadeTransition.setToValue(0.3f);
        fadeTransition.setCycleCount(2);
        fadeTransition.setAutoReverse(true);
         
        TranslateTransition translateTransition
                = new TranslateTransition(Duration.millis(2000), imageView);
        translateTransition.setFromX(0);
        translateTransition.setToX(350);
        translateTransition.setCycleCount(2);
        translateTransition.setAutoReverse(true);
 
        RotateTransition rotateTransition
                = new RotateTransition(Duration.millis(3000), imageView);
        rotateTransition.setByAngle(180f);
        rotateTransition.setCycleCount(4);
        rotateTransition.setAutoReverse(true);
 
        ScaleTransition scaleTransition
                = new ScaleTransition(Duration.millis(2000), imageView);
        scaleTransition.setToX(2f);
        scaleTransition.setToY(2f);
        scaleTransition.setCycleCount(2);
        scaleTransition.setAutoReverse(true);
 
        ParallelTransition parallelTransition = 
                 new ParallelTransition();
        parallelTransition.getChildren().addAll(
                fadeTransition,
                translateTransition,
                rotateTransition,
                scaleTransition);
         parallelTransition.setCycleCount(1);
         //parallelTransition.play();
         
        SequentialTransition sequentialTransition = 
                new SequentialTransition();
        sequentialTransition.getChildren().addAll(
                fadeTransition,
                translateTransition,
                rotateTransition,
                scaleTransition);
        sequentialTransition.setCycleCount(1);
        //sequentialTransition.play();
        //
         
        Button btnParallelTransitionPlay = 
                new Button("parallelTransition.play");
        btnParallelTransitionPlay.setOnAction((ActionEvent event) -> {
            parallelTransition.play();
        });
 
        Button btnSequentialTransitionPlay = 
                new Button("sequentialTransition.play");
        btnSequentialTransitionPlay.setOnAction((ActionEvent event) -> {
            sequentialTransition.play();
        });
 
        HBox hbox = new HBox();
        hbox.getChildren().addAll(
                btnParallelTransitionPlay,
                imageView,
                btnSequentialTransitionPlay);
         
        Label labelInfo = new Label();
        labelInfo.setText(
                "java.version: " + System.getProperty("java.version") + "\n"
                + "javafx.runtime.version: " + System.getProperty("javafx.runtime.version") + "\n"
                + "os.name: " + System.getProperty("os.name")
        );
         
        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelInfo, hbox);
         
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
 
        Scene scene = new Scene(root, 700, 250);
 
        primaryStage.setTitle("java-buddy: Transition Example "
                + "- ParallelTransition/SequentialTransition");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}


JavaFX Reflection Effect

Example of using JavaFX Reflection Effect, javafx.scene.effect.Reflection.


package javafx_reflection;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Reflection extends Application {

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        Scene scene = new Scene(root, 700, 600, Color.WHITE);

        Reflection reflection = new Reflection();
        
        Button btn = new Button("Click Me");
        btn.setOnAction((ActionEvent event) -> {
            if(btn.getText().equals("Click Me")){
                btn.setText("Hello! Thanks...");
                reflection.setBottomOpacity(1.0);
            }else{
                btn.setText("Click Me");
                reflection.setBottomOpacity(0.0);
            }
            
        });
        btn.setEffect(reflection);

        Text textView = new Text(50, 150, "java-buddy.blogspot.com");
        textView.setFill(Color.BLUE);
        textView.setFont(Font.font("Monospaced", 40));
        textView.setEffect(reflection);
        
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));
        imageView.setEffect(reflection);
        
        Slider slider = new Slider();
        slider.setMin(-50);
        slider.setMax(250);
        slider.setValue(0);
        slider.valueProperty().addListener(
                (ObservableValue<? extends Number> ov, 
                        Number old_val, Number new_val) -> {
            reflection.setTopOffset((double) new_val);
        });

        Label labelInfo = new Label();
        labelInfo.setText(
                "java.version: " + System.getProperty("java.version") + "\n"
                + "javafx.runtime.version: " + System.getProperty("javafx.runtime.version") + "\n"
                + "os.name: " + System.getProperty("os.name")
        );
        labelInfo.setEffect(reflection);
        
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(20, 20, 20, 20));
        vBox.getChildren().addAll(labelInfo, imageView, textView, btn, slider);

        root.getChildren().add(vBox);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}




Next: JavaFX Transition Animation with Reflection effect

Tuesday, September 15, 2015

JavaFX example of Transition Animation, ParallelTransition and SequentialTransition

JavaFX example of Transition Animation, ParallelTransition and SequentialTransition.


JavaFX_TransitionExample.java
package javafx_transitionexample;

import javafx.animation.FadeTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.RotateTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TransitionExample extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Transition Example
        //ref: http://docs.oracle.com/javafx/2/animations/basics.htm
        ImageView imageView = new ImageView(new Image("http://goo.gl/kYEQl"));

        FadeTransition fadeTransition
                = new FadeTransition(Duration.millis(3000), imageView);
        fadeTransition.setFromValue(1.0f);
        fadeTransition.setToValue(0.3f);
        fadeTransition.setCycleCount(2);
        fadeTransition.setAutoReverse(true);
        
        TranslateTransition translateTransition
                = new TranslateTransition(Duration.millis(2000), imageView);
        translateTransition.setFromX(0);
        translateTransition.setToX(350);
        translateTransition.setCycleCount(2);
        translateTransition.setAutoReverse(true);

        RotateTransition rotateTransition
                = new RotateTransition(Duration.millis(3000), imageView);
        rotateTransition.setByAngle(180f);
        rotateTransition.setCycleCount(4);
        rotateTransition.setAutoReverse(true);

        ScaleTransition scaleTransition
                = new ScaleTransition(Duration.millis(2000), imageView);
        scaleTransition.setToX(2f);
        scaleTransition.setToY(2f);
        scaleTransition.setCycleCount(2);
        scaleTransition.setAutoReverse(true);

        ParallelTransition parallelTransition = 
                 new ParallelTransition();
        parallelTransition.getChildren().addAll(
                fadeTransition,
                translateTransition,
                rotateTransition,
                scaleTransition);
         parallelTransition.setCycleCount(1);
         //parallelTransition.play();
        
        SequentialTransition sequentialTransition = 
                new SequentialTransition();
        sequentialTransition.getChildren().addAll(
                fadeTransition,
                translateTransition,
                rotateTransition,
                scaleTransition);
        sequentialTransition.setCycleCount(1);
        //sequentialTransition.play();
        //
        
        Button btnParallelTransitionPlay = 
                new Button("parallelTransition.play");
        btnParallelTransitionPlay.setOnAction((ActionEvent event) -> {
            parallelTransition.play();
        });

        Button btnSequentialTransitionPlay = 
                new Button("sequentialTransition.play");
        btnSequentialTransitionPlay.setOnAction((ActionEvent event) -> {
            sequentialTransition.play();
        });

        HBox hbox = new HBox();
        hbox.getChildren().addAll(
                btnParallelTransitionPlay,
                imageView,
                btnSequentialTransitionPlay);
        
        Label labelInfo = new Label();
        labelInfo.setText(
                "java.version: " + System.getProperty("java.version") + "\n"
                + "javafx.runtime.version: " + System.getProperty("javafx.runtime.version") + "\n"
                + "os.name: " + System.getProperty("os.name")
        );
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelInfo, hbox);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 700, 250);

        primaryStage.setTitle("java-buddy: Transition Example "
                + "- ParallelTransition/SequentialTransition");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}





Next: JavaFX Transition Animation with Reflection effect

Sunday, September 13, 2015

OpenCV Computer Vision with Java

Create multiplatform computer vision desktop and web applications using the combination of OpenCV and Java

About This Book
  • Set up Java API for OpenCV to create popular Swing-based Graphical User Interfaces (GUIs)
  • Process videos and images in real-time with closer to native performance
  • Make use of rock solid Java web application development practices to create engaging augmented reality experience and work with depth images from a Kinect device
Who This Book Is For
If you are a Java developer, student, researcher, or hobbyist wanting to create computer vision applications in Java then this book is for you. If you are an experienced C/C++ developer who is used to working with OpenCV, you will also find this book very useful for migrating your applications to Java.

All you need is basic knowledge of Java, with no prior understanding of computer vision required, as this book will give you clear explanations and examples of the basics.

What You Will Learn
  • Create powerful GUIs for computer vision applications with panels, scroll panes, radio buttons, sliders, windows, and mouse interaction using the popular Swing GUI widget toolkit
  • Stretch, shrink, warp, and rotate images, as well as apply image transforms to find edges, lines, and circles, and even use Discrete Fourier Transforms (DFT)
  • Detect foreground or background regions and work with depth images with a Kinect device
  • Learn how to add computer vision capabilities to rock solid Java web applications allowing you to upload photos and create astonishing effects
  • Track faces and apply mixed reality effects such as adding virtual hats to uploaded photos
  • Filter noisy images, work with morphological operators, use flood fill, and threshold the important regions of an image
  • Open and process video streams from webcams or video files
In Detail
OpenCV 3.0 Computer Vision with Java is a practical tutorial guide that explains fundamental tasks from computer vision while focusing on Java development. This book will teach you how to set up OpenCV for Java and handle matrices using the basic operations of image processing such as filtering and image transforms. It will also help you learn how to use Haar cascades for tracking faces and to detect foreground and background regions with the help of a Kinect device. It will even give you insights into server-side OpenCV. Each chapter is presented with several projects that are ready to use. The functionality of these projects is found in many classes that allow developers to understand computer vision principles and rapidly extend or customize the projects for their needs.

Saturday, September 12, 2015

Test-Driven Java Development

Invoke TDD principles for end-to-end application development with Java

About This Book
  • Explore the most popular TDD tools and frameworks and become more proficient in building applications
  • Create applications with better code design, fewer bugs, and higher test coverage, enabling you to get them to market quickly
  • Implement test-driven programming methods into your development workflows
Who This Book Is For
If you're an experienced Java developer and want to implement more effective methods of programming systems and applications, then this book is for you.

What You Will Learn
  • Explore the tools and frameworks required for effective TDD development
  • Perform the Red-Green-Refactor process efficiently, the pillar around which all other TDD procedures are based
  • Master effective unit testing in isolation from the rest of your code
  • Design simple and easily maintainable codes by implementing different techniques
  • Use mocking frameworks and techniques to easily write and quickly execute tests
  • Develop an application to implement behaviour-driven development in conjunction with unit testing
  • Enable and disable features using Feature Toggles
In Detail
Test-driven development (TDD) is a development approach that relies on a test-first procedure that emphasises writing a test before writing the necessary code, and then refactoring the code to optimize it.

The value of performing TDD with Java, one of the most established programming languages, is to improve the productivity of programmers, the maintainability and performance of code, and develop a deeper understanding of the language and how to employ it effectively.

Starting with the basics of TDD and reasons why its adoption is beneficial, this book will take you from the first steps of TDD with Java until you are confident enough to embrace the practice in your day-to-day routine.

You'll be guided through setting up tools, frameworks, and the environment you need, and will dive right in to hands-on exercises with the goal of mastering one practice, tool, or framework at a time. You'll learn about the Red-Green-Refactor procedure, how to write unit tests, and how to use them as executable documentation.

With this book you'll also discover how to design simple and easily maintainable code, work with mocks, utilise behaviour-driven development, refactor old legacy code, and release a half-finished feature to production with feature toggles.

You will finish this book with a deep understanding of the test-driven development methodology and the confidence to apply it to application programming with Java.

Style and approach
An easy-to-follow, hands-on guide to building applications through effective coding practices. This book covers practical examples by introducing different problems, each one designed as a learning exercise to help you understand each aspect of TDD.

Thursday, September 10, 2015

Add data to JavaFX LineChart, and shift out the oldest data.


JavaFX example to update LineChart: user enter new data to the LineChart associated series, and remove the oldest item from the series. I tried three approachs to achieve the goal. The first one is obviously wrong. Check the code to know my implement.


package javafx_linechart;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_LineChart extends Application {
    
    Label label1, label2, label3;
    XYChart.Series series1, series2, series3;
    final int MAX_NUM = 10;
    @Override
    public void start(Stage primaryStage) {

        TextField textField = new TextField();
        Button btn = new Button();
        btn.setText("Add item");
        btn.setOnAction((ActionEvent event) -> {
            try{
                int i = Integer.parseInt(textField.getText());
                System.out.println(String.valueOf(i));
                
                removeAndAdd(series1, i);
                reduceSeriesXValue(series2, i);
                shiftSeriesYValue(series3, i);
                
                printSeries(series1, label1);
                printSeries(series2, label2);
                printSeries(series3, label3);
                
            }catch (NumberFormatException ex){
                System.out.println(ex.toString());
            }
        });
        
        label1 = new Label();
        label2 = new Label();
        label3 = new Label();
        
        //prepare LineChart 1
        final NumberAxis xAxis1 = new NumberAxis();
        final NumberAxis yAxis1 = new NumberAxis();
        final LineChart<Number,Number> lineChart1 = 
                new LineChart<>(xAxis1,yAxis1);
        series1 = new XYChart.Series();
        series1.setName("series1");
        lineChart1.getData().add(series1);
        
        //prepare LineChart 2
        final NumberAxis xAxis2 = new NumberAxis();
        final NumberAxis yAxis2 = new NumberAxis();
        final LineChart<Number,Number> lineChart2 = 
                new LineChart<>(xAxis2,yAxis2);
        series2 = new XYChart.Series();
        series2.setName("series2");
        lineChart2.getData().add(series2);
        
        //prepare LineChart 3
        final NumberAxis xAxis3 = new NumberAxis();
        final NumberAxis yAxis3 = new NumberAxis();
        final LineChart<Number,Number> lineChart3 = 
                new LineChart<>(xAxis3,yAxis3);
        series3 = new XYChart.Series();
        series3.setName("series3");
        lineChart3.getData().add(series3);
        
        //init dummy data
        for(int i=0; i<MAX_NUM; i++){
            series1.getData().add(new XYChart.Data(i, i));
            series2.getData().add(new XYChart.Data(i, i));
            series3.getData().add(new XYChart.Data(i, i));
        }
        
        printSeries(series1, label1);
        printSeries(series2, label2);
        printSeries(series3, label3);
        
        VBox vBox1 = new VBox();
        vBox1.getChildren().addAll(lineChart1, label1);
        VBox vBox2 = new VBox();
        vBox2.getChildren().addAll(lineChart2, label2);
        VBox vBox3 = new VBox();
        vBox3.getChildren().addAll(lineChart3, label3);
        
        HBox chartBox = new HBox();
        chartBox.getChildren().addAll(vBox1, vBox2, vBox3);
        
        CheckBox cbAnimated = new CheckBox("animated");
        cbAnimated.setSelected(true);
        cbAnimated.selectedProperty().addListener(
                (ObservableValue<? extends Boolean> observable, 
                        Boolean oldValue, Boolean newValue) -> {
            lineChart1.setAnimated(newValue);
            lineChart2.setAnimated(newValue);
            lineChart3.setAnimated(newValue);
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(cbAnimated, textField, btn, chartBox);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 1000, 650);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    //Remove the first item, and add the new item - WRONG result!
    private void removeAndAdd(XYChart.Series series, int newValue){
        series.getData().remove(0);
        XYChart.Data newData = 
                new XYChart.Data(series.getData().size(), newValue);
        series.getData().add(newData);
    }
    
    //remove the first item
    //reduce XValue of all items by 1
    //add the new item
    public void reduceSeriesXValue(XYChart.Series series, int newValue){
        series.getData().remove(0);
        int numOfPoint = series.getData().size();
        for(int i=0; i<numOfPoint; i++){
            //reduce XValue
            XYChart.Data<Number, Number> data = 
                    (XYChart.Data<Number, Number>)series.getData().get(i);
            int x = (int)data.getXValue();
            data.setXValue(x-1);
        }
        
        series.getData().add(new XYChart.Data(numOfPoint, newValue));

    }
    
    //Shift all YValue
    //add the new item
    public void shiftSeriesYValue(XYChart.Series series, int newValue){
        int numOfPoint = series.getData().size();
        for(int i=0; i<numOfPoint-1; i++){
            XYChart.Data<Number, Number> ShiftDataUp = 
                    (XYChart.Data<Number, Number>)series.getData().get(i+1);
            Number shiftValue = ShiftDataUp.getYValue();
            XYChart.Data<Number, Number> ShiftDataDn = 
                    (XYChart.Data<Number, Number>)series.getData().get(i);
            ShiftDataDn.setYValue(shiftValue);
        }
        XYChart.Data<Number, Number> lastData = 
            (XYChart.Data<Number, Number>)series.getData().get(numOfPoint-1);
        lastData.setYValue(newValue);
    }
    
    //display the data of series
    private void printSeries(XYChart.Series series, Label label){
        String printOut = "";
        int numOfPoint = series.getData().size();
        for(int i=0; i<numOfPoint; i++){
            XYChart.Data<Number, Number> data = 
                    (XYChart.Data<Number, Number>)series.getData().get(i);
            printOut += i + " - " + data.getXValue() 
                    + " : " + data.getYValue() + "\n";
        }
        
        label.setText(printOut);
    }
    
    public static void main(String[] args) {
        launch(args);
    }
    
}

Sunday, September 6, 2015

Mastering NetBeans

Master building complex applications with NetBeans to become more proficient programmers


About This Book
  • Customize NetBeans to fit your unique needs
  • Excel in NetBeans IDE, learning the shortcuts and hidden features to become more productive
  • A comprehensive guide to become more productive at application development using NetBeans IDE
Who This Book Is For
If you are a competent developer who wants to fast-track your application development with NetBeans IDE, then this book is for you. Reasonable knowledge and an understanding of Java programming and NetBeans IDE is assumed.

What You Will Learn
  • Install NetBeans either from a distribution package or from source code
  • Test, debug, and run production code using the NetBeans IDE
  • Use external services such as PaaS environments and web services
  • Create desktop applications using Swing tools
  • Manage and configure relational databases
  • Build a Java business model and web tiers using Java EE and Spring technologies
  • Explore web services both with XML and RESTful approaches
  • Handle external services such as databases , Maven repositories, and cloud providers
  • Extend NetBeans for those situations where you require more from your IDE
In Detail
With the increasing complexity of software development and the abundance of tools available, learning your IDE in-depth will instantly increase your developer productivity. NetBeans is the only IDE that can be downloaded with Java itself and provides you with many cutting edge features not readily available with many IDEs. The IDE also provides a great set of tools for PHP and C/C++ developers. It is free and open source and has a large community of users and developers around the world.

This book will teach you to ace NetBeans IDE and make use of it in creating Java business and web services. It will help you to become a proficient developer and use NetBeans for software development. You will learn effective third-party interaction and enable yourself for productive database development.

Moving on, you will see how to create EJB projects and write effective and efficient web applications. Then you will learn how to use Swing and manage and configure a relational database. By the end of the book, you will be able to handle external services such as databases, Maven repositories, and cloud providers, and extend your NetBeans when you require more from your IDE.

Style and approach
An easy-to-follow yet comprehensive guide to help you master the exhaustive range of NetBeans features in order to become more efficient at Java programing. More advanced topics are covered in each chapter, with subjects grouped according to their complexity as well as their utility.

Friday, September 4, 2015

JavaFX example - set ViewPort of ImageView


Example to change ViewPort of ImageView, and rotate ImageView.

package javafx_imageview_viewport;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ImageView_Viewport extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        ImageView imageView1 = new ImageView(new Image("http://goo.gl/kYEQl"));
        
        //Example to rotate ImageView
        Image image2 = new Image("http://goo.gl/kYEQl");
        Rectangle2D viewportRect2 = new Rectangle2D(
                image2.getWidth()/4, 
                image2.getHeight()/4, 
                image2.getWidth()*3/4, 
                image2.getHeight()*3/4);
        ImageView imageView2 = new ImageView(image2);
        imageView2.setViewport(viewportRect2);
        
        Slider sliderRotate = new Slider();
        sliderRotate.setMin(0);
        sliderRotate.setMax(360);
        sliderRotate.setValue(0);
        sliderRotate.valueProperty().addListener(
                (ObservableValue<? extends Number> observable, 
                        Number oldValue, Number newValue) -> {
            imageView2.setRotate((double)newValue);
        });
        
        //Example to change ViewPort
        Image image3 = new Image("http://goo.gl/kYEQl");
        Rectangle2D viewportRect3 = new Rectangle2D(
                0, 
                0, 
                image3.getWidth(), 
                image3.getHeight());
        ImageView imageView3 = new ImageView(image3);
        imageView3.setViewport(viewportRect3);
        
        Slider sliderViewPort = new Slider();
        sliderViewPort.setMin(0);
        sliderViewPort.setMax(1.0);
        sliderViewPort.setValue(1.0);
        sliderViewPort.valueProperty().addListener(
                (ObservableValue<? extends Number> observable, 
                        Number oldValue, Number newValue) -> {
            Rectangle2D newViewportRect3 = new Rectangle2D(
                    0,
                    0,
                    (double)newValue*image3.getWidth(),
                    (double)newValue*image3.getHeight());
            imageView3.setViewport(newViewportRect3);
        });
        

        VBox vBox = new VBox();
        vBox.getChildren().addAll(imageView1, 
                imageView2, sliderRotate,
                imageView3, sliderViewPort);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 350);
        
        primaryStage.setTitle("java-buddy: ImageVIew ViewPort");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}