Saturday, December 27, 2014

JavaFX + ImageIO: Convert PNG file to JPG

This example show how to choose PNG file using JavaFX FileChooser, open with ImageIO (actually any supported image format), and save in JPG using ImageIO.


package javafximagefilechooser;

import java.awt.Color;
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.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
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 JavaFXImageFileChooser extends Application {

    @Override
    public void start(Stage primaryStage) {
        
        final FileChooser fileChooser = new FileChooser();
        final Button openButton = new Button("Open Image");

        openButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public void handle(final ActionEvent e) {
                    setExtFilters(fileChooser);
                    File file = fileChooser.showOpenDialog(primaryStage);
                    if (file != null) {
                        openNewImageWindow(file);
                    }
                }
            });

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

    public static void main(String[] args) {
        launch(args);
    }
    
    private void setExtFilters(FileChooser chooser){
        chooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );
    }
    
    private void openNewImageWindow(File file){
        Stage secondStage = new Stage();
        
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu("File");
        MenuItem menuItem_Save = new MenuItem("Save Image");
        menuFile.getItems().addAll(menuItem_Save);
        menuBar.getMenus().addAll(menuFile);
        
        Label name = new Label(file.getAbsolutePath());
        
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file);
        } catch (IOException ex) {
            Logger.getLogger(JavaFXImageFileChooser.class.getName()).log(Level.SEVERE, null, ex);
        }

        ImageView imageView = new ImageView();

        final BufferedImage imageToWrite = 
            new BufferedImage(
                bufferedImage.getWidth(),
                bufferedImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        imageToWrite.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
        
        menuItem_Save.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("Save Image");
                
                File file = fileChooser.showSaveDialog(secondStage);
                
                if (file != null) {
                    try {
                        ImageIO.write(imageToWrite, "jpg", file);
                    } catch (IOException ex) {
                        Logger.getLogger(
                            JavaFXImageFileChooser.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        final VBox vbox = new VBox();
        vbox.setAlignment(Pos.CENTER);
        vbox.setSpacing(10);
        vbox.setPadding(new Insets(0, 10, 0, 10));
        vbox.getChildren().addAll(name, imageView);
        
        imageView.setFitHeight(400);
        imageView.setPreserveRatio(true);
        imageView.setImage(SwingFXUtils.toFXImage(bufferedImage, null));
        imageView.setSmooth(true);
        imageView.setCache(true);
        
        Scene scene = new Scene(new VBox(), 400, 350);
        ((VBox)scene.getRoot()).getChildren().addAll(menuBar, vbox);
        
        secondStage.setTitle(file.getName());
        secondStage.setScene(scene);
        secondStage.show();
    }
    
}

Thursday, December 25, 2014

JavaFX FileChooser, open and save image file

Example to open and save png files, using JavaFX FileChooser.


package javafximagefilechooser;

import java.awt.Desktop;
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.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
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 JavaFXImageFileChooser extends Application {

    @Override
    public void start(Stage primaryStage) {
        
        final FileChooser fileChooser = new FileChooser();
        final Button openButton = new Button("Open Image");

        openButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public void handle(final ActionEvent e) {
                    setExtFilters(fileChooser);
                    File file = fileChooser.showOpenDialog(primaryStage);
                    if (file != null) {
                        openNewImageWindow(file);
                    }
                }
            });

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

    public static void main(String[] args) {
        launch(args);
    }
    
    private void setExtFilters(FileChooser chooser){
        chooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );
    }
            
    private void openNewImageWindow(File file){
        Stage secondStage = new Stage();
        
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu("File");
        MenuItem menuItem_Save = new MenuItem("Save Image");
        menuFile.getItems().addAll(menuItem_Save);
        menuBar.getMenus().addAll(menuFile);
        
        Label name = new Label(file.getAbsolutePath());
        Image image = new Image(file.toURI().toString());
        ImageView imageView = new ImageView();
        
        menuItem_Save.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("Save Image");
                
                File file = fileChooser.showSaveDialog(secondStage);
                if (file != null) {
                    try {
                        ImageIO.write(SwingFXUtils.fromFXImage(imageView.getImage(),
                                null), "png", file);
                    } catch (IOException ex) {
                        Logger.getLogger(
                            JavaFXImageFileChooser.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        final VBox vbox = new VBox();
        vbox.setAlignment(Pos.CENTER);
        vbox.setSpacing(10);
        vbox.setPadding(new Insets(0, 10, 0, 10));
        vbox.getChildren().addAll(name, imageView);
        
        imageView.setFitHeight(400);
        imageView.setPreserveRatio(true);
        imageView.setImage(image);
        imageView.setSmooth(true);
        imageView.setCache(true);
        
        Scene scene = new Scene(new VBox(), 400, 350);
        ((VBox)scene.getRoot()).getChildren().addAll(menuBar, vbox);
        
        secondStage.setTitle(file.getName());
        secondStage.setScene(scene);
        secondStage.show();
    }
    
}

Wednesday, December 24, 2014

To list ImageIO supported read/write file format on your system

Example to list suffixes, format names and MIME types of supported image format on your system, by ImageIO, for read and write.

package javasupportedimageformat;

import javax.imageio.ImageIO;

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

    public static void main(String[] args) {
        
        //reader support
        System.out.println("ImageIO reader supported file suffixes:");
        String readerFileSuffixes[] = ImageIO.getReaderFileSuffixes();
        for(String f : readerFileSuffixes){
            System.out.println(f);
        }
        System.out.println();
        
        System.out.println("ImageIO reader supported format names:");
        String readerFormatNames[] = ImageIO.getReaderFormatNames();
        for(String f : readerFormatNames){
            System.out.println(f);
        }
        System.out.println();
        
        System.out.println("ImageIO reader supported MIME types:");
        String readerMIMETypes[] = ImageIO.getReaderMIMETypes();
        for(String f : readerMIMETypes){
            System.out.println(f);
        }
        System.out.println();
        
        //writer support
        System.out.println("ImageIO writer supported file suffixes:");
        String writerFileSuffixes[] = ImageIO.getWriterFileSuffixes();
        for(String f : writerFileSuffixes){
            System.out.println(f);
        }
        System.out.println();
        
        System.out.println("ImageIO writer supported format names:");
        String writerFormatNames[] = ImageIO.getWriterFormatNames();
        for(String f : writerFormatNames){
            System.out.println(f);
        }
        System.out.println();
        
        System.out.println("ImageIO writer supported MIME types:");
        String writerMIMETypes[] = ImageIO.getWriterMIMETypes();
        for(String f : writerMIMETypes){
            System.out.println(f);
        }
        System.out.println();
    }
    
}

Monday, December 22, 2014

Building home gateways with Eclipse SmartHome



Despite the buzz around the Internet of Things (IoT) there are still many devices, systems and protocols for home automation that cannot be directly hooked up to your wifi and used through IP.

To enable smartphone apps to access them and to integrate them with other devices, an IP gateway is required - if it connects to more than just one specific system, this is usually called a home gateway.

Eclipse SmartHome is a flexible software framework for such home gateways. Being initiated by the popular open-source project openHAB, the Eclipse SmartHome project leads the way from the niche to the mass market by fostering industry adoption and by introducing new concepts for setup and configuration procedures of such solutions.

In this webinar you will learn about the concepts of Eclipse SmartHome, what services it provides and how to build a customized solution with it.

Slides are available on Slideshare: http://slideshare.net/xthirtynine/eclipse-smart-home-webinar

Saturday, December 13, 2014

get NetworkInterface and my IP address

Example to display name and ip address of NetworkInterface.

reference: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html


package javamyipaddress;

import static java.lang.System.out;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

/**
 *
 * @web http://java-buddy.blogspot.com/
 * ref: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html
 */
public class JavaMyIpAddress {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }

}

Saturday, December 6, 2014

JavaFX example, setCursor() and getCursor()

JavaFX example to set cursor type to node by calling setCursor() and get cursor type by calling getCursor().


package javafxhello;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXHello extends Application {

    Scene scene;

    Button createButton(Cursor cursor) {
        Button btn = new Button();
        btn.setMnemonicParsing(false);
        //Sets the value of the property mnemonicParsing false to display '_'.
        /*
         MnemonicParsing property to enable/disable text parsing. 
         If this is set to true, then the Label text will be parsed 
         to see if it contains the mnemonic parsing character '_'. 
         When a mnemonic is detected the key combination will be 
         determined based on the succeeding character, 
         and the mnemonic added.
         */
        btn.setCursor(cursor);
        btn.setText(btn.getCursor().toString());
        
        btn.setOnAction((ActionEvent event) -> {
            Node src = (Node) event.getSource();
            scene.setCursor(src.getCursor());
        });
        return btn;
    }

    @Override
    public void start(Stage primaryStage) {

        VBox vBox = new VBox();
        scene = new Scene(vBox, 300, 250);

        Button btnCLOSED_HAND = createButton(Cursor.CLOSED_HAND);
        Button btnCROSSHAIR = createButton(Cursor.CROSSHAIR);
        Button btnDEFAULT = createButton(Cursor.DEFAULT);
        Button btnDISAPPEAR = createButton(Cursor.DISAPPEAR);
        Button btnE_RESIZE = createButton(Cursor.E_RESIZE);
        Button btnH_RESIZE = createButton(Cursor.H_RESIZE);
        Button btnHAND = createButton(Cursor.HAND);
        Button btnMOVE = createButton(Cursor.MOVE);
        Button btnN_RESIZE = createButton(Cursor.N_RESIZE);
        Button btnNE_RESIZE = createButton(Cursor.NE_RESIZE);
        Button btnNONE = createButton(Cursor.NONE);
        Button btnNW_RESIZE = createButton(Cursor.NW_RESIZE);
        Button btnOPEN_HAND = createButton(Cursor.OPEN_HAND);
        Button btnS_RESIZE = createButton(Cursor.S_RESIZE);
        Button btnSE_RESIZE = createButton(Cursor.SE_RESIZE);
        Button btnSW_RESIZE = createButton(Cursor.SW_RESIZE);
        Button btnTEXT = createButton(Cursor.TEXT);
        Button btnV_RESIZE = createButton(Cursor.V_RESIZE);
        Button btnW_RESIZE = createButton(Cursor.W_RESIZE);
        Button btnWAIT = createButton(Cursor.WAIT);

        vBox.getChildren().addAll(
                btnCLOSED_HAND, btnCROSSHAIR, btnDEFAULT,
                btnDISAPPEAR, btnE_RESIZE, btnH_RESIZE,
                btnHAND, btnMOVE, btnN_RESIZE, btnNE_RESIZE,
                btnNONE, btnNW_RESIZE, btnOPEN_HAND, btnS_RESIZE,
                btnSE_RESIZE, btnSW_RESIZE, btnTEXT, btnV_RESIZE,
                btnW_RESIZE, btnWAIT);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

Wednesday, December 3, 2014

JavaFX example of using scene.nodeOrientationProperty().setValue(NodeOrientation.RIGHT_TO_LEFT)



package javafxhello;

import javafx.application.Application;
import javafx.geometry.NodeOrientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXHello extends Application {
    
    @Override
    public void start(Stage primaryStage) {

        HBox hBox123 = new HBox();
        hBox123.getChildren().addAll(
            new Label(" Label 1 "), 
            new Label(" Label 2 "),
            new Label(" Label 3 ")
        );
        
        HBox hBoxABC = new HBox();
        hBoxABC.getChildren().addAll(
            new Label(" Label A "), 
            new Label(" Label B "),
            new Label(" Label C ")
        );
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBox123, hBoxABC);
        
        Scene scene = new Scene(vBox, 300, 250);
        
        scene.nodeOrientationProperty().setValue(NodeOrientation.RIGHT_TO_LEFT);
        //hBox123.nodeOrientationProperty().setValue(NodeOrientation.RIGHT_TO_LEFT);
        //hBoxABC.nodeOrientationProperty().setValue(NodeOrientation.RIGHT_TO_LEFT);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Tuesday, December 2, 2014

Java ME Embedded for Raspberry Pi, Release 8.1

The Oracle Java ME Embedded release 8.1 software for the Raspberry Pi platform is a ready-to-run binary for use with an off-the-shelf Raspberry Pi Model B board. The Oracle Java ME Embedded release 8.1 software underwent sanity check for use with a Raspberry Pi Model B+ board. See the Usage Notes for more details.

The Oracle Java ME Embedded software uses an optimized platform stack for small embedded devices, which includes the Connected Limited Device Configuration (CLDC) HotSpot Implementation (Java Virtual Machine) version 8, the Micro Edition Embedded Profile (MEEP) application environment, the Generic Connection Framework (GCF) API, and enhanced support for various Java Specification Requests (JSRs).

Release Notes

~ Getting Started Guide


Thursday, November 27, 2014

Example of ListChangeListener for javafx.collections.ObservableList


package javafxobservablelistchangelistener;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXObservableListChangeListener extends Application {
    
    int count = 0;
    ObservableList observableList;
    
    @Override
    public void start(Stage primaryStage) {
        
        observableList = FXCollections.observableArrayList();
        observableList.addListener(new ListChangeListener(){

            @Override
            public void onChanged(ListChangeListener.Change c) {
                System.out.println("\nonChanged()");

                while(c.next()){
                    System.out.println("next: ");
                    if(c.wasAdded()){
                        System.out.println("- wasAdded");
                    }
                    if(c.wasPermutated()){
                        System.out.println("- wasPermutated");
                    }
                    if(c.wasRemoved()){
                        System.out.println("- wasRemoved");
                    }
                    if(c.wasReplaced()){
                        System.out.println("- wasReplaced");
                    }
                    if(c.wasUpdated()){
                        System.out.println("- wasUpdated");
                    }
                }
                
                for(Object i : observableList){
                    System.out.println(i);
                }
            }
        });

        Button btnAdd = new Button();
        btnAdd.setText("Add item");
        btnAdd.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                observableList.add(count);
                count++;
            }
        });
        
        Button btnRemove = new Button();
        btnRemove.setText("Remove item");
        btnRemove.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                
                int size = observableList.size();
                if(size > 0){
                    observableList.remove(size-1);
                }
            }
        });
        
        Button btnReplace = new Button();
        btnReplace.setText("Replace last item (+1)");
        btnReplace.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                
                int size = observableList.size();
                if(size > 0){
                    observableList.set(
                        size-1, 
                        (int)observableList.get(size-1)+1);
                }
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(btnAdd, btnRemove, btnReplace);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


Wednesday, November 19, 2014

Java in a Nutshell

Java in a Nutshell

The latest edition of Java in a Nutshell is designed to help experienced Java programmers get the most out of Java 7 and 8, but it’s also a learning path for new developers. Chock full of examples that demonstrate how to take complete advantage of modern Java APIs and development best practices, the first section of this thoroughly updated book provides a fast-paced, no-fluff introduction to the Java programming language and the core runtime aspects of the Java platform.

The second section is a reference to core concepts and APIs that shows you how to perform real programming work in the Java environment.
  • Get up to speed on language details, including Java 8 changes
  • Learn object-oriented programming, using basic Java syntax
  • Explore generics, enumerations, annotations, and lambda expressions
  • Understand basic techniques used in object-oriented design
  • Examine concurrency and memory, and how they’re intertwined
  • Work with Java collections and handle common data formats
  • Delve into Java’s latest I/O APIs, including asynchronous channels
  • Use Nashorn to execute JavaScript on the Java Virtual Machine
  • Become familiar with development tools in OpenJDK


Thursday, November 13, 2014

Building the Internet of Things with Java


Streamed live on Nov 6, 2014

It may seem hard to get started with the Internet of Things (IoT) with so many technologies, protocols, hardware platforms, … involved. In this session, Benjamin Cabé from the Eclipse Foundation will cover all you need to know to start building IoT solutions using Java and open technologies like MQTT, CoAP, OSGi, or LWM2M. A real-life application (smart greenhouse) will be used as an example and you will most likely leave the session craving for building a very similar application yourself!

Speaker: Benjamin Cabé

Benjamin Cabé is IoT evangelist at the Eclipse Foundation. He advocates the use of open and innovative technologies for the Internet of Things and likes building crazy machines with Arduino kits and all kinds of open hardware platforms. You can find him online on Twitter (@kartben) or on his blog: http://blog.benjamin-cabe.com.

Saturday, November 8, 2014

List and check ConditionalFeature

javafx.application.ConditionalFeature defines a set of conditional (optional) features. These features may not be available on all platforms. An application that wants to know whether a particular feature is available may query this using the Platform.isSupported() function. Using a conditional feature on a platform that does not support it will not cause an exception. In general, the conditional feature will just be ignored. See the documentation for each feature for more detail.

package javaconditionalfeature;

import javafx.application.ConditionalFeature;
import javafx.application.Platform;

public class JavaConditionalFeature {


    public static void main(String[] args) {
        for (ConditionalFeature c : ConditionalFeature.values()){
            System.out.print(c + " : ");
            if(Platform.isSupported(c)){
                System.out.println("supported");
            }else{
                System.out.println("not supported");
            }
        }
    }    
}

Wednesday, October 22, 2014

Beginning Java 8 APIs, Extensions and Libraries: Swing, JavaFX, JavaScript, JDBC and Network Programming APIs

Beginning Java 8 APIs, Extensions and Libraries: Swing, JavaFX, JavaScript, JDBC and Network Programming APIs completes the Apress learning Java journey and is a comprehensive approach to learning the Java programming language extensions and available APIs and libraries, including the new JavaFX APIs.

This book covers the key extensions of the Java programming language such as Swing, JavaFX, network programming, and JDBC. Each topic starts with a discussion of the topic's background. A step-by-step process, with small snippets of Java code, provides easy-to-follow instructions. At the end of a topic, a complete and ready-to-run Java program is provided. This book contains over 130 images and diagrams to help you visualize and better understand the topics. More than 130 complete programs allow you to practice and quickly learn the topics.

The Swing chapters discuss various aspects of working with a GUI, from the very basic concepts of developing a Swing application, to the most advanced topics, such as decorating a Swing component with a JLayer, drag-and-drop features, Synth Skinnable L&F, etc.

The chapter on network programming covers the basics of network technologies first, and then, the advanced topics of network programming, using a Java class library. It covers IPv4 and IPv6, addressing schemes, subnetting, supernetting, multicasting, TCP/IP sockets, UPD sockets, asynchronous socket I/O, etc.

The chapter on JDBC provides the details of connecting and working with databases such as Oracle, SQL Server, MySQL, DB2, Java DB (Apache Derby), Sybase, Adaptive Server Anywhere, etc. It contains a complete discussion on processing a ResultSet and a RowSet. It discusses how to use the RowSetFactory, to obtain a RowSet object of a specific type. Working with Large Objects (LOBs), such as Blob, Clob, and NClob, is covered in detail with Java code examples and database scripts.

What you’ll learn
  • How to extend your Java skills beyond the fundamental object oriented concepts and core language features
  • How to apply Java Swing for building Java front ends or user interfaces (UIs)
  • How to build small Java applications called applets
  • How to do Java network programming
  • How to connect with databases using JDBC APIs
  • How to work with JavaFX, RMI (Remote Method Invocation), and JNI (Java Native Interface)
  • How to use scripting in Java, including coverage of the Nashorn engine
Who this book is for
This tutorial is for Java programmers who are familiar with the fundamentals of the Java language and Java programming, who are now ready to call upon the power of extended Java functionality available from the huge array of Java APIs, extensions and libraries.

Table of Contents
1. Introduction to Swing
2. Swing Components
3. Advanced Swing
4. Applets
5. Network Programming
6. JDBC APIs
7. Java Remote Method Invocation
8. Java Native Interface
9. Introduction to JavaFX
10. Scripting in Java

Friday, October 17, 2014

Get various parts from URL

package javaurlget;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaURLget {

    public static void main(String[] args) {
        String src = "http://java-buddy.blogspot.com/search/label/java8";
        try {
            URL srcURL = new URL(src);
            
            System.out.println(srcURL.toString());
            System.out.println("Host: " + srcURL.getHost());
            System.out.println("Path: " + srcURL.getPath());
            System.out.println("Port: " + srcURL.getPort());
            System.out.println("Protocol: " + srcURL.getProtocol());
            System.out.println("Authority: " + srcURL.getAuthority());
            System.out.println("File: " + srcURL.getFile());
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(JavaURLget.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
}



Java 8 Recipes, 2nd Edition

Java 8 Recipes offers solutions to common programming problems encountered while developing Java-based applications. Fully updated with the newest features and techniques available, Java 8 Recipes provides code examples involving Lambdas, embedded scripting with Nashorn, the new date-time API, stream support, functional interfaces, and much more. Especial emphasis is given to features such as lambdas that are newly introduced in Java 8. Content is presented in the popular problem-solution format: Look up the programming problem that you want to solve. Read the solution. Apply the solution directly in your own code. Problem solved!

The problem-solution approach sets Java 8 Recipes apart. Java 8 Recipes is focused less on the language itself and more on what you can do with it that is useful. The book respects your time by always focusing on a task that you might want to perform using the language. Solutions come first. Explanations come later. You are free to crib from the book and apply the code examples directly to your own projects.
  • Covers the newly-released Java 8, including a brand new chapter on lambdas
  • Focuses especially on up-and-coming technologies such as Project Nashorn and Java FX 2.0
  • Respects your time by focusing on practical solutions you can implement in your own code
What you’ll learn
  • Develop Java SE applications using the latest in Java SE technology
  • Exploit the newly-introduced lambda features in Java 8
  • Build dynamic web applications with JavaScript and Project Nashorn
  • Create great-looking user interfaces with Java FX 2.0
  • Generate graphics and work with media such as sound and video
  • Add internationalization support to your Java applications
Who this book is for
Java 8 Recipes is aimed mainly at intermediate and experienced Java programmers. If you're past the point of being able to write "Hello, World", then you'll find Java 8 Recipes to be chock full of interesting and useful programming solutions to help you achieve your goals and meet with success in your Java programming projects.

Table of Contents
Chapter 1: Language Basics
Chapter 2: Java 8 JDK Enhancements
Chapter 3: Strings
Chapter 4: Numbers and Dates
Chapter 5: Object-Oriented Java
Chapter 6: Lambda Expressions
Chapter 7: Data Structures, Conditionals, and Collections
Chapter 8: Input and Output
Chapter 9: Exceptions and Logging
Chapter 10: Concurrency
Chapter 11: Debugging and Unit Testing
Chapter 12: Unicode, Internationalization, and Currency Codes
Chapter 13: Working with Databases
Chapter 14: JavaFX Fundamentals
Chapter 15: Graphics with JavaFX
Chapter 16: Media with JavaFX
Chapter 17: JavaFX on the Web
Chapter 18: Nashorn and Scripting
Chapter 19: Email
Chapter 20: XML Processing
Chapter 21: Networking
Chapter 22: Java 8 Security Enhancements

Thursday, October 16, 2014

Mastering JavaFX 8 Controls

Design and Deploy High-Performance JavaFX Controls: Mastering JavaFX 8 Controls (Oracle (McGraw-Hill))

Deliver state-of-the-art applications with visually stunning UIs. Mastering JavaFX 8 Controls provides clear instructions, detailed examples, and ready-to-use code samples. Find out how to work with the latest JavaFX APIs, configure UI components, automatically generate FXML, build cutting-edge controls, and effectively apply CSS styling. Troubleshooting, tuning, and deployment are also covered in this Oracle Press guide.
  • Understand the properties of JavaFX 8 controls and APIs
  • Create custom controls, transformations, and layouts
  • Work from JavaFX Scene Graph and Scene Builder
  • Visualize data models using advanced control types
  • Use ListView, TableView, and TreeView APIs
  • Handle audio and video content using JavaFX media classes
  • Maximize separation between UI and application logic using FXML
  • Style controls and applications using CSS
  • Extend functionality of Swing and SWT applications with JavaFX
Code examples in the book are available for download.

Mastering Lambdas: Java Programming in a Multicore World

The Definitive Guide to Lambda Expressions: Mastering Lambdas: Java Programming in a Multicore World

Mastering Lambdas: Java Programming in a Multicore World describes how the lambda-related features of Java SE 8 will enable Java to meet the challenges of next-generation parallel hardware architectures. The book explains how to write lambdas, and how to use them in streams and in collection processing, providing code examples throughout. You'll learn how to use lambda expressions to take full advantage of performance improvements provided by today's multicore hardware. This Oracle Press book covers:
  • Why lambdas were needed, and how they will change Java programming
  • Syntax of lambda expressions
  • The basic operation of streams and pipelines
  • Using collectors and reduction to end pipelines
  • Creating streams
  • Spliterators, the fork/join framework, and exceptions
  • Examining stream performance with microbenchmarking
  • API evolution using default methods

Monday, October 13, 2014

Java EE 7: The Big Picture

The Definitive Guide to Java Platform, Enterprise Edition 7

Java EE 7: The Big Picture uniquely explores the entire Java EE 7 platform in an all-encompassing style while examining each tier of the platform in enough detail so that you can select the right technologies for specific project needs. In this authoritative guide, Java expert Danny Coward walks you through the code, applications, and frameworks that power the platform. Take full advantage of the robust capabilities of Java EE 7, increase your productivity, and meet enterprise demands with help from this Oracle Press resource.
  • Explore the features of the Java servlet model and Java servlet API
  • Create dynamic web content with JavaServer Pages and JavaServer Faces
  • Build websites for nonbrowser clients with JAX-RS
  • Push data to web clients using Java WebSockets
  • Secure web applications
  • Work with web component APIs
  • Maximize enterprise beans for multithreading, asynchronous processes, transactions, and more
  • Access relational databases with the Java Database Connectivity APIs and the Java Persistence API
  • Understand the packaging and deployment mechanisms of Java EE applications
  • Work with Java EE Contexts and Dependency Injection
  • Secure enterprise beans in a Java EE application
  • Enable parallel processing with Java EE concurrency APIs

Friday, October 10, 2014

IoT Dev Challenge Student Winners: ePot

JavaOne interview with the student winners of the OTN IoT Developer Challenge.

Saturday, September 27, 2014

Java 8 in Action: Lambdas, Streams, and functional-style programming

Java 8 in Action: Lambdas, Streams, and functional-style programming

Java 8 in Action is a clearly written guide to the new features of Java 8. The book covers lambdas, streams, and functional-style programming. With Java 8's functional features you can now write more concise code in less time, and also automatically benefit from multicore architectures. It's time to dig in!

Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.

About the Book

Every new version of Java is important, but Java 8 is a game changer. Java 8 in Action is a clearly written guide to the new features of Java 8. It begins with a practical introduction to lambdas, using real-world Java code. Next, it covers the new Streams API and shows how you can use it to make collection-based code radically easier to understand and maintain. It also explains other major Java 8 features including default methods, Optional, CompletableFuture, and the new Date and Time API.

This book is written for programmers familiar with Java and basic OO programming.

What's Inside
  • How to use Java 8's powerful new features
  • Writing effective multicore-ready applications
  • Refactoring, testing, and debugging
  • Adopting functional-style programming
  • Quizzes and quick-check questions
About the Authors

Raoul-Gabriel Urma is a software engineer, speaker, trainer, and PhD candidate at the University of Cambridge. Mario Fusco is an engineer at Red Hat and creator of the lambdaj library. Alan Mycroft is a professor at Cambridge and cofounder of the Raspberry Pi Foundation.

Table of Contents

PART 1 FUNDAMENTALS
  • Java 8: why should you care?
  • Passing code with behavior parameterization
  • Lambda expressions
PART 2 FUNCTIONAL-STYLE DATA PROCESSING
  • Introducing streams
  • Working with streams
  • Collecting data with streams
  • Parallel data processing and performance
PART 3 EFFECTIVE JAVA 8 PROGRAMMING
  • Refactoring, testing, and debugging
  • Default methods
  • Using Optional as a better alternative to null
  • CompletableFuture: composable asynchronousprogramming
  • New Date and Time API
PART 4 BEYOND JAVA 8
  • Thinking functionally
  • Functional programming techniques
  • Blending OOP and FP: comparing Java 8 and Scala
  • Conclusions and where next for Java
APPENDIXES
  • Miscellaneous language updates
  • Miscellaneous library updates
  • Performing multiple operations in parallelon a stream
  • Lambdas and JVM bytecode

Monday, September 22, 2014

JavaFX 8 ColorPicker to fill Background

JavaFX 8 example to implement ColorPicker and set background color on Action EventHandler.


package javafxcolorpicker;

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXColorPicker extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        
        ColorPicker colorPicker = new ColorPicker();
        
        colorPicker.setOnAction(new EventHandler(){

            @Override
            public void handle(Event event) {
                Paint fill = colorPicker.getValue();
                BackgroundFill backgroundFill = 
                    new BackgroundFill(fill, 
                            CornerRadii.EMPTY, 
                            Insets.EMPTY);
                Background background = new Background(backgroundFill);
                root.setBackground(background);
            }
        });

        root.getChildren().add(colorPicker);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Friday, September 19, 2014

JavaFX Rich Client Programming on the NetBeans Platform

JavaFX Rich Client Programming on the NetBeans Platform

JavaFX is a state-of-the-art graphics toolkit that is now built into Java and can be easily integrated with the NetBeans Platform. With JavaFX, you can create advanced user interfaces, manipulate media, generate graphical effects and animations, and much more. The NetBeans Platform provides a framework for building robust, modular applications with long life expectancies. Together, JavaFX and the NetBeans Platform provide the basis for creating visually appealing, industrial-strength applications.

Focusing on JavaFX as the front end for rich client applications, this guide’s examples cover JavaFX 8 with the NetBeans Platform, NetBeans IDE, and Java 8. Gail and Paul Anderson fully explain JavaFX and its relationship with the NetBeans Platform architecture, and systematically show Java developers how to use them together effectively. Each concept and technique is supported by clearly written code examples, proven through extensive classroom teaching.

Coverage includes
  • Background basics with Java, JavaFX, and UI events
  • Building loosely coupled applications
  • NetBeans Platform Modules and Lookup
  • NetBeans Platform Nodes, Explorer Views, and Actions
  • Building CRUD-based applications
  • Integrating JavaFX with a Swing-based framework
  • Using JavaFX Charts with the NetBeans Platform
  • Using the NetBeans Platform File System and Data System
  • Keeping the UI responsive

Tuesday, September 16, 2014

Example of getSimpleName()

The getSimpleName() method returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

This example modify from last post to list superclasses with simple name.


package javagetsuperclass;

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

    public static void main(String[] args) {

        JavaGetSuperClass me = new JavaGetSuperClass();
        me.doSomething();
        
        SubJavaGetSuperClass subMe = new SubJavaGetSuperClass();
        subMe.doSomething();
        
        Class testClass = javafx.scene.chart.AreaChart.class;
        printClassInfo(testClass);
    }

    public void doSomething(){
        printClassInfo(this.getClass());
    }
    
    static private void printClassInfo(Class someClass){

        StringBuilder info = new StringBuilder();
        
        info.append("someClass: ").append(someClass).append("\n");
        
        do{
            someClass = someClass.getSuperclass();
            if(someClass!=null){
                info.append("superClass: ").append(someClass.getSimpleName()).append("\n");
            }else{
                info.append("superClass: ").append("null").append("\n");
            }
            
        }while(someClass != null);
        
        info.append("=====").append("\n");
        System.out.println(info);
    }

}

class SubJavaGetSuperClass extends JavaGetSuperClass{
        
}

Example of using getSuperclass()

The getSuperclass() method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.

This example list the superclasses of a class.


package javagetsuperclass;

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

    public static void main(String[] args) {

        JavaGetSuperClass me = new JavaGetSuperClass();
        me.doSomething();
        
        SubJavaGetSuperClass subMe = new SubJavaGetSuperClass();
        subMe.doSomething();
        
        Class testClass = javafx.scene.chart.AreaChart.class;
        printClassInfo(testClass);
    }

    public void doSomething(){
        printClassInfo(this.getClass());
    }
    
    static private void printClassInfo(Class someClass){

        StringBuilder info = new StringBuilder();
        
        info.append("someClass: ").append(someClass).append("\n");
        
        do{
            someClass = someClass.getSuperclass();
            info.append("superClass: ").append(someClass).append("\n");
        }while(someClass != null);
        
        info.append("=====").append("\n");
        System.out.println(info);
    }

}

class SubJavaGetSuperClass extends JavaGetSuperClass{
        
}

Saturday, September 13, 2014

Google Translate (with tts) on JavaFX, using java-google-translate-text-to-speech

This example show how to implement Google Translate, with text-to-speech, on JavaFX application, using java-google-translate-text-to-speech.


Read the post "JavaFX with text-to-speech, with java-google-translate-text-to-speech" to know how to add lib of java-google-translate-text-to-speech for Netbeans.

package javafx_texttospeech;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import com.gtranslate.Translator;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javazoom.jl.decoder.JavaLayerException;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TextToSpeech extends Application {
    
    Lang lang;
    ObservableList langNameList;
    ObservableList langPrefixList;
    
    String selectedPrefix;
    String srcPrefix = Language.ENGLISH;

    @Override
    public void start(Stage primaryStage) {
        
        lang = new Lang();
        langNameList = lang.getNameList();
        langPrefixList = lang.getPrefixList();

        Label labelPrefix = new Label();
        
        ChoiceBox targetLangBox = new ChoiceBox(langNameList);
        targetLangBox.getSelectionModel().selectFirst();
        
        Label labelTranslated = new Label();
        
        selectedPrefix = (String) langPrefixList.get(
            targetLangBox.getSelectionModel().getSelectedIndex());
        labelPrefix.setText(selectedPrefix);
        
        targetLangBox.getSelectionModel().selectedIndexProperty()
            .addListener(new ChangeListener(){

            @Override
            public void changed(ObservableValue observable, 
                Object oldValue, Object newValue) {
                
                selectedPrefix = (String) langPrefixList.get((int)newValue);
                labelPrefix.setText(selectedPrefix);
            }
        });

        TextField srcTextField = new TextField();
        
        Button btnTranslate = new Button("Translate");
        btnTranslate.setOnAction((ActionEvent event) -> {
            Translator translator = Translator.getInstance();
            String translatedText = translator.translate(
                    srcTextField.getText(), 
                    srcPrefix, 
                    selectedPrefix);
            labelTranslated.setText(translatedText);
        });
        
        Button btnSpeakSrc = new Button("Speak");
        btnSpeakSrc.setOnAction((ActionEvent event) -> {
            String toSpeak = srcTextField.getText();
            if(!toSpeak.equals("")){
                try {
                    InputStream sound = null;
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio(toSpeak, srcPrefix);
                    audio.play(sound);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        
        Button btnSpeakDest = new Button("Speak");
        btnSpeakDest.setOnAction((ActionEvent event) -> {
            
            String toSpeak = labelTranslated.getText();
            if(!toSpeak.equals("")){
                try {
                    InputStream sound = null;
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio(toSpeak, selectedPrefix);
                    audio.play(sound);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            
        });
        
        VBox vBoxSrc = new VBox();
        VBox vBoxDest = new VBox();
        vBoxSrc.getChildren().addAll(
            new Label("Source: ENGLISH (en)"), 
            srcTextField, 
            btnTranslate, 
            btnSpeakSrc);
        
        vBoxDest.getChildren().addAll(
            new Label("Translate to:"), 
            targetLangBox, 
            labelPrefix, 
            labelTranslated, 
            btnSpeakDest);

        TilePane tilePane = new TilePane();
        tilePane.setPrefColumns(3);
        tilePane.setPadding(new Insets(5, 5, 5, 5));
        tilePane.setVgap(5);
        tilePane.setHgap(5);
        tilePane.setStyle("-fx-background-color: D0D0D0;");
        tilePane.setAlignment(Pos.TOP_CENTER);

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                InputStream sound = null;
                try {
                    System.out.println("Hello World!");
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio("Hello World", Language.ENGLISH);
                    audio.play(sound);
                } catch (IOException | JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        sound.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        tilePane.getChildren().addAll(vBoxSrc, vBoxDest);

        StackPane root = new StackPane();
        root.getChildren().add(tilePane);

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

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

class Lang {

    private Map<String, String> mapLang;

    Lang() {
        mapLang = new TreeMap<>();
        init();
    }

    private void init() {
        mapLang.put("af", "AFRIKAANS");
        mapLang.put("sq", "ALBANIAN");
        mapLang.put("ar", "ARABIC");
        mapLang.put("hy", "ARMENIAN");
        mapLang.put("az", "AZERBAIJANI");
        mapLang.put("eu", "BASQUE");
        mapLang.put("be", "BELARUSIAN");
        mapLang.put("bn", "BENGALI");
        mapLang.put("bg", "BULGARIAN");
        mapLang.put("ca", "CATALAN");
        mapLang.put("zh-CN", "CHINESE");
        mapLang.put("hr", "CROATIAN");
        mapLang.put("cs", "CZECH");
        mapLang.put("da", "DANISH");
        mapLang.put("nl", "DUTCH");
        mapLang.put("en", "ENGLISH");
        mapLang.put("et", "ESTONIAN");
        mapLang.put("tl", "FILIPINO");
        mapLang.put("fi", "FINNISH");
        mapLang.put("fr", "FRENCH");
        mapLang.put("gl", "GALICIAN");
        mapLang.put("ka", "GEORGIAN");
        mapLang.put("de", "GERMAN");
        mapLang.put("el", "GREEK");
        mapLang.put("gu", "GUJARATI");
        mapLang.put("ht", "HAITIAN_CREOLE");
        mapLang.put("iw", "HEBREW");
        mapLang.put("hi", "HINDI");
        mapLang.put("hu", "HUNGARIAN");
        mapLang.put("is", "ICELANDIC");
        mapLang.put("id", "INDONESIAN");
        mapLang.put("ga", "IRISH");
        mapLang.put("it", "ITALIAN");
        mapLang.put("ja", "JAPANESE");
        mapLang.put("kn", "KANNADA");
        mapLang.put("ko", "KOREAN");
        mapLang.put("la", "LATIN");
        mapLang.put("lv", "LATVIAN");
        mapLang.put("lt", "LITHUANIAN");
        mapLang.put("mk", "MACEDONIAN");
        mapLang.put("ms", "MALAY");
        mapLang.put("mt", "MALTESE");
        mapLang.put("no", "NORWEGIAN");
        mapLang.put("fa", "PERSIAN");
        mapLang.put("pl", "POLISH");
        mapLang.put("pt", "PORTUGUESE");
        mapLang.put("ro", "ROMANIAN");
        mapLang.put("ru", "RUSSIAN");
        mapLang.put("sr", "SERBIAN");
        mapLang.put("sk", "SLOVAK");
        mapLang.put("sl", "SLOVENIAN");
        mapLang.put("es", "SPANISH");
        mapLang.put("sw", "SWAHILI");
        mapLang.put("sv", "SWEDISH");
        mapLang.put("ta", "TAMIL");
        mapLang.put("te", "TELUGU");
        mapLang.put("th", "THAI");
        mapLang.put("tr", "TURKISH");
        mapLang.put("uk", "UKRAINIAN");
        mapLang.put("ur", "URDU");
        mapLang.put("vi", "VIETNAMESE");
        mapLang.put("cy", "WELSH");
        mapLang.put("yi", "YIDDISH");
        mapLang.put("af", "AFRIKAANS");
        mapLang.put("sq", "ALBANIAN");
        mapLang.put("ar", "ARABIC");
        mapLang.put("hy", "ARMENIAN");
        mapLang.put("az", "AZERBAIJANI");
        mapLang.put("eu", "BASQUE");
        mapLang.put("be", "BELARUSIAN");
        mapLang.put("bn", "BENGALI");
        mapLang.put("bg", "BULGARIAN");
        mapLang.put("ca", "CATALAN");
        mapLang.put("zh-CN", "CHINESE_SIMPLIFIED");
        mapLang.put("zh-TW", "CHINESE_TRADITIONAL");
        mapLang.put("hr", "CROATIAN");
        mapLang.put("cs", "CZECH");
        mapLang.put("da", "DANISH");
        mapLang.put("nl", "DUTCH");
        mapLang.put("et", "ESTONIAN");
        mapLang.put("tl", "FILIPINO");
        mapLang.put("fi", "FINNISH");
        mapLang.put("fr", "FRENCH");
        mapLang.put("gl", "GALICIAN");
        mapLang.put("ka", "GEORGIAN");
        mapLang.put("de", "GERMAN");
        mapLang.put("el", "GREEK");
        mapLang.put("gu", "GUJARATI");
        mapLang.put("ht", "HAITIAN_CREOLE");
        mapLang.put("iw", "HEBREW");
        mapLang.put("hi", "HINDI");
        mapLang.put("hu", "HUNGARIAN");
        mapLang.put("is", "ICELANDIC");
        mapLang.put("id", "INDONESIAN");
        mapLang.put("ga", "IRISH");
        mapLang.put("it", "ITALIAN");
        mapLang.put("ja", "JAPANESE");
        mapLang.put("kn", "KANNADA");
        mapLang.put("ko", "KOREAN");
        mapLang.put("la", "LATIN");
        mapLang.put("lv", "LATVIAN");
        mapLang.put("lt", "LITHUANIAN");
        mapLang.put("mk", "MACEDONIAN");
        mapLang.put("ms", "MALAY");
        mapLang.put("mt", "MALTESE");
        mapLang.put("no", "NORWEGIAN");
        mapLang.put("fa", "PERSIAN");
        mapLang.put("pl", "POLISH");
        mapLang.put("pt", "PORTUGUESE");
        mapLang.put("ro", "ROMANIAN");
        mapLang.put("ru", "RUSSIAN");
        mapLang.put("sr", "SERBIAN");
        mapLang.put("sk", "SLOVAK");
        mapLang.put("sl", "SLOVENIAN");
        mapLang.put("es", "SPANISH");
        mapLang.put("sw", "SWAHILI");
        mapLang.put("sv", "SWEDISH");
        mapLang.put("ta", "TAMIL");
        mapLang.put("te", "TELUGU");
        mapLang.put("th", "THAI");
        mapLang.put("tr", "TURKISH");
        mapLang.put("uk", "UKRAINIAN");
        mapLang.put("ur", "URDU");
        mapLang.put("vi", "VIETNAMESE");
        mapLang.put("cy", "WELSH");
        mapLang.put("yi", "YIDDISH");
 
    }
    
    public ObservableList getNameList(){

        return FXCollections.observableArrayList(mapLang.values().toArray());

    }
    
    public ObservableList getPrefixList(){

        return FXCollections.observableArrayList(mapLang.keySet().toArray());

    }

}

JavaFX Choice Box example

JavaFX Choice Box is UI controls that provide support for quickly selecting between a few options, something like spinner.


Example code:
package javafxchoicebox;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXChoiceBox extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Label label1 = new Label();
        Label label2 = new Label();
        
        ChoiceBox choiceBox = new ChoiceBox(
            FXCollections.observableArrayList(
                "java-buddy", "Java", "Buddy")
        );
        choiceBox.getSelectionModel().selectFirst();
        choiceBox.getSelectionModel().selectedItemProperty()
            .addListener((ObservableValue observable, 
                    Object oldValue, Object newValue) -> {
                label1.setText((String)newValue);
        });
        
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction((ActionEvent event) -> {
            String selected = choiceBox.getSelectionModel()
                    .getSelectedItem().toString();
            label2.setText("Hello " + selected);
        });
        
        VBox root = new VBox();
        root.getChildren().addAll(choiceBox, btn, label1, label2);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

JavaFX TilePane example


package javafxtilepane;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXTilePane extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        TilePane tilePane = new TilePane();
        tilePane.setPrefColumns(3);
        tilePane.setPadding(new Insets(5, 5, 5, 5));
        tilePane.setVgap(5);
        tilePane.setHgap(5);
        tilePane.setStyle("-fx-background-color: D0D0D0;");
        tilePane.setAlignment(Pos.CENTER);
        
        Button btn = new Button();
        btn.setText("Say \n'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello");
            }
             
        });
        
        Button btn1 = new Button();
        btn1.setText("Horizontal");
        btn1.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                tilePane.setOrientation(Orientation.HORIZONTAL);
            }
        });
        
        Button btn2 = new Button();
        btn2.setText("Vertical");
        btn2.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                tilePane.setOrientation(Orientation.VERTICAL);
            }
        });
        
        tilePane.getChildren().addAll(btn1, btn, btn2);
        //set all button equal width and height
        ObservableList<Node> children = tilePane.getChildren();
        children.forEach(button->{
            ((Button)button).setMinWidth(Button.USE_PREF_SIZE);
            ((Button)button).setMaxWidth(Double.MAX_VALUE);
            ((Button)button).setMinHeight(Button.USE_PREF_SIZE);
            ((Button)button).setMaxHeight(Double.MAX_VALUE);
        });

        Scene scene = new Scene(tilePane, 300, 250);
        
        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Friday, September 12, 2014

JavaFX with text-to-speech, with java-google-translate-text-to-speech

To add text-to-speech function to JavaFX application, we can using java-google-translate-text-to-speech, an Api unofficial with the main features of Google Translate in Java.

This video show how to add download and add the library of java-google-translate-text-to-speech tyo Netbeans, and create Hello World with text-of-speech in Netbeans.


package javafx_texttospeech;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import java.io.IOException;
import java.io.InputStream;
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.StackPane;
import javafx.stage.Stage;
import javazoom.jl.decoder.JavaLayerException;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TextToSpeech extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                InputStream sound = null;
                try {
                    System.out.println("Hello World!");
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio("Hello World", Language.ENGLISH);
                    audio.play(sound);
                } catch (IOException | JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        sound.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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


- Google Translater (with tts) on JavaFX

Sunday, August 24, 2014

Update JavaFX BarChart in background thread, to display /proc/meminfo.

Similar to previous post "Display /proc/meminfo on JavaFX PieChart", this example show how to display memory usage, retrieved from /proc/meminfo, on JavaFX BarChart.



Another main point of this post is to show the different of loading data in various stage. There are three position in the code to load barchart data.
  • At position A: call prepareMemInfo() to load barchart data in JavaFX Application Thread, before UI show.
  • At position B, call prepareMemInfo() to load barchart data in JavaFX Application Thread, after UI show.
  • At position C, start another thread to load barchart data.
    In this case, another question rised: in prepareMemInfo(), the file /proc/meminfo is parsed in sequency, but add data to series2 in Application Thread by calling Platform.runLater(). May be it will not in the same sequency. <- I'm not sure here.
Check this video to know the different:


package javafx_meminfo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

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

    final static String FILE_MEMINFO = "/proc/meminfo";

    private final TableView<Record> tableMem = new TableView<>();
    ObservableList<Record> listRecords = FXCollections.observableArrayList();

    XYChart.Series series1 = new XYChart.Series();  //load in Application Thread
    XYChart.Series series2 = new XYChart.Series();  //load in Background Thread
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    final BarChart<String, Number> barChart = new BarChart<>(xAxis, yAxis);

    @Override
    public void start(Stage primaryStage) {

        //position A - run in UI Thread, before UI show
        //prepareMemInfo();
        
        tableMem.setEditable(false);

        TableColumn colMemField = new TableColumn("Field");
        colMemField.setMinWidth(150);
        colMemField.setCellValueFactory(
            new PropertyValueFactory<>("memField"));

        TableColumn colMemValue = new TableColumn("Value");
        colMemValue.setMinWidth(100);
        colMemValue.setCellValueFactory(
            new PropertyValueFactory<>("memValue"));

        TableColumn colMemUnit = new TableColumn("Unit");
        colMemUnit.setMinWidth(50);
        colMemUnit.setCellValueFactory(
            new PropertyValueFactory<>("memUnit"));

        TableColumn colMemQty = new TableColumn("Qty");
        colMemQty.setMinWidth(200);
        colMemQty.setCellValueFactory(
            new PropertyValueFactory<>("memQty"));

        tableMem.setItems(listRecords);
        tableMem.getColumns().addAll(colMemField,
            colMemValue, colMemUnit, colMemQty);
        
        //Create a dummy ProgressBar running 
        ProgressTask progressTask = new ProgressTask();
        ProgressBar progressBar = new ProgressBar();
        progressBar.setProgress(0);
        progressBar.progressProperty().bind(progressTask.progressProperty());
        
        new Thread(progressTask).start();
        //---
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(tableMem, progressBar);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

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

        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();

        //Open second window
        barChart.setTitle(FILE_MEMINFO);
        xAxis.setLabel("Field");
        yAxis.setLabel("Qty");
        barChart.getData().addAll(series1, series2);

        StackPane secondaryLayout = new StackPane();
        secondaryLayout.getChildren().add(barChart);

        Scene secondScene = new Scene(secondaryLayout, 500, 400);

        Stage secondStage = new Stage();
        secondStage.setTitle("Second Stage");
        secondStage.setScene(secondScene);

        //Set position of second window, related to primary window.
        secondStage.setX(primaryStage.getX() + 250);
        secondStage.setY(primaryStage.getY() + 20);
        secondStage.show();

        //position B - run in UI Thread, after UI show
        //prepareMemInfo();
        
        //position C - run in background Thread
        new Thread(BackgroundPrepareMemoInfo).start();
    }

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

    Runnable BackgroundPrepareMemoInfo = () -> {
        prepareMemInfo();
    };

    private void prepareMemInfo() {
        
        //dummy delay
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaFX_meminfo.class.getName()).log(Level.SEVERE, null, ex);
        }

        Stream<String> streamMemInfo = readFile(FILE_MEMINFO);
        streamMemInfo.forEach((line) -> {
            System.out.println(line);

            //split one line by whitespace/grouped whitespaces
            String[] oneLine = line.split("\\s+");

            for (String ele : oneLine) {
                System.out.println(ele);
            }

            System.out.println("---");

            String rField = "";
            int rMemValue = 0;
            String rMemUnit = "";

            if (oneLine.length <= 3) {
                if (oneLine.length == 3) {
                    rField = oneLine[0];
                    rMemValue = Integer.parseInt(oneLine[1]);
                    rMemUnit = oneLine[2];
                } else if (oneLine.length == 2) {
                    rField = oneLine[0];
                    rMemValue = Integer.parseInt(oneLine[1]);
                    rMemUnit = "B";
                } else if (oneLine.length == 1) {
                    rField = oneLine[0];
                    rMemValue = 0;
                    rMemUnit = "B";
                }

                Record record = new Record(
                    rField, rMemValue, rMemUnit);
                listRecords.add(record);

                if (Platform.isFxApplicationThread()) {
                    //It's running in UI Thread
                    series1.getData().add(new XYChart.Data(record.getMemField(), record.getMemQty()));
                } else {
                    //It's running in background Thread
                    Platform.runLater(() -> {
                        series2.getData().add(new XYChart.Data(record.getMemField(), record.getMemQty()));
                    });
                }

            }

        });
    }

    private Stream<String> readFile(String filePath) {
        Path path = Paths.get(filePath);

        Stream<String> fileLines = null;
        try {
            fileLines = Files.lines(path);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_meminfo.class.getName()).log(Level.SEVERE, null, ex);
        }

        return fileLines;
    }

    public static class Record {

        private final SimpleStringProperty memField;
        private final SimpleIntegerProperty memValue;
        private final SimpleStringProperty memUnit;
        private final SimpleFloatProperty memQty;

        private Record(String memField, int memValue, String memUnit) {
            this.memField = new SimpleStringProperty(memField);

            this.memValue = new SimpleIntegerProperty(memValue);
            this.memUnit = new SimpleStringProperty(memUnit);
            if (memValue == 0) {
                this.memQty = new SimpleFloatProperty(0.0f);
            } else if (memUnit.equalsIgnoreCase("MB")) {
                this.memQty = new SimpleFloatProperty((float) memValue * 1000000.0f);
            } else if (memUnit.equalsIgnoreCase("kB")) {
                this.memQty = new SimpleFloatProperty((float) memValue * 1000.0f);
            } else {
                this.memQty = new SimpleFloatProperty((float) memValue);
            }
        }

        public String getMemField() {
            return memField.get();
        }

        public int getMemValue() {
            return memValue.get();
        }

        public String getMemUnit() {
            return memUnit.get();
        }

        public float getMemQty() {
            return memQty.get();
        }

    }
    
    final int MAX_PROGRESS = 50;
    class ProgressTask extends Task<Void>{
         
        @Override
        protected Void call() throws Exception {
            for (int i = 1; i <= MAX_PROGRESS; i++) {
                updateProgress(i, MAX_PROGRESS);
                Thread.sleep(200);
            }
            return null;
        }
         
    }

}