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

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

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

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

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


Subscribe to: Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /