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