Category Archives: Books

Raspberry Pi with Java: Programming the IoT (Book Review)

 

Cover of the book Raspberry Pi with Java: Programming the Internet of Things (IoT)

Raspberry Pi with Java: Programming the Internet of Things (IoT) Embedded Application Development for Home and Industry

Greetings Java/JavaFX/Raspberry Pi fans!,

Before beginning this book review it was brought to my attention that I had to disclose lawyer speak in order to comply with FTC rules relating to bloggers.

Disclosure of Material Connection: I received this book free from Oracle Press / McGraw-Hill Education (Publisher) In exchange for a book review. I was not required to write a positive review. The opinions I have expressed are my own. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”

Introduction

It is the year 2016, and by now we should be at more than a billion connected devices related to the Internet of Things (IoT) which numerous firms have predicted. If you’re like me a person who loves to tinker and discover things you have probably heard about the Raspberry Pi. On my journey to learn all things Pi I’ve come across many books related to the Raspberry Pi that utilized various programming languages, however when it came down to the Java language the books were pretty scarce.

Look no further, a new book has finally arrived that focuses on Java technologies to drive your Raspberry Pi projects. In this blog entry I will be reviewing the book Raspberry Pi with Java: Programming the Internet of Things (IoT) by Stephen Chin with James L. Weaver  (Oracle Press). Technical editor by Mark Heckler.

Book Review

The two book authors are some of the most respected in the IoT, Java and JavaFX communities. Both Stephen Chin (Oracle) and James Weaver (Pivotal) are Java champions who are renowned speakers at many major developer conferences worldwide. The technical editor Mark Heckler (Pivotal) is also a well known Java geek who also speaks at many prominate conferences around the world.

For starters the authors begin with a very good introductory and summary of the chapters. After the summary of the chapters the book points out two links to download the source code for the book. Other programming books with source code usually point to their publishing company’s website. Fortunately, this book provides two places to obtain the source code. One at the publishing company (www.mhprofessional.com) and the other is hosted at the Github (https://github.com/RaspberryPiWithJava).

Chapter 1: Baking Pie

The authors gets you started by listing all the component parts and software necessary to develop on the Raspberry Pi. The instructions on how to setup and configure the Raspbian OS are thoroughly explained. I like how the authors discuss how to connect all the different Raspberry Pi models to your network. Keep in mind that the book was written prior to the announcement of the Raspberry Pi Zero model, so the book has no mention of it.

In chapter 1 they show you how to connect your Raspberry Pi using Ethernet or Wireless connection. After, successfully connected, the authors show you how to ssh into your Raspberry Pi remotely from the three major OS platforms (MacOS, Linux and Windows) through your terminal (command-line console). Once able to ssh into your Raspberry Pi you will be able to code/compile and run a Hello World Java console application.

Chapter 2: Your First Java Project

In Chapter 2, the authors begin by walking you through setting up the NetBeans IDE to remotely debug live running code on a Raspberry Pi. Once you get comfortable with the developer workflow, the authors start out with a cool (hot) project on brewing the perfect cup of coffee! When beginning a project the authors always start off with a Bill of Materials detailing what and where to buy parts for a project.

In this chapter it delves into APIs (JSR 80) that allows your Java code to communicate with USB ports (usb4j). The authors show you how to read information from a USB port on an electronic scale device. The scale is used to measure the weight of things such as ground coffee beans. This chapter ends with the discussion of the topic of Commercial Licensing and FOSS. Learning about licensing options can help you navigate through legal matters if you decide to go commercial with your Java/Raspberry Pi product.

Chapter 3: Binary Timer

The authors goal in this chapter focuses on how to use GPIO (general purpose input output) pins. The GPIO pins are how the Raspberry Pi talks to analog and digital components such as LEDs, DC motors and light sensors. In this section you will learn the fundamentals of electronics such as power, Ohms law and what resistors you will need to purchase, etc. I love one of the tip blocks on “What is the Worst You Can Do to Your Raspberry Pi“. This tip allows you to not feel intimidated when approaching a Raspberry Pi by explaining how rugged the Raspberry Pi computer actually is, and how to prevent mishaps or damaging the Pi.

The authors mention two Java libraries commonly used for accessing GPIO pins on the Raspberry Pi. One being the Device I/O library and the other Pi4J. In this section the benefits of using each library are fully detailed. This chapter is very hands-on by creating a basic project using LEDs on a breadboard that can count down in binary. Many Fritzing diagrams are presented for step-by-step instruction on how to wire-up components properly. In this chapter the authors mention helpful troubleshooting tips such as Java code to solve the button debouncing issues when dealing with physical buttons or switches in your circuits. Lastly, this chapter provides bonus content that teaches you how to measure and compare performance metrics when using the two Java libraries Device I/O library and Pi4J by turning LEDs on and off very rapidly. Here, both memory-mapped access (Low-level) vs Sysfs access (Higher-level) were compared. This will help you decide which strategy is best depending on your use-case.

Chapter 4: IoT Hat

Now with the fundamentals of the Raspberry Pi, Java and basic electronics out of the way, you can now tackle a magical project that will astonish friends and family. This project involves creating a magicians top hat with the ability to know what playing card was chosen without seeing the face of the card. The authors teach you about how to configure your Raspberry Pi to enable I2C, SPI, and UART protocols. This chapter focuses on learning about NFC/RFID devices such as smart card readers. Beware: This section involves soldering so get your flux on. Here, you will learn how to communicate with an RFID reader’s breakout board.

This project also teaches you about compactness and portability (cordless) because you will be hiding stuff in a top hat. To make things portable the Pi will use a WiFi adapter and USB cell phone charging battery. The authors will also take you through native libraries required for Java to communicate with the NFC device so don’t be alarmed if you encounter Make files and permissions (typical in the Linux world).

Chapter 5: Line Runner

After learning skills for compactness and portability from chapter 4 the authors show you how to reuse your skills to build an autonomous robot! This should be the very reason to get this book. In the Bill of Materials all the parts (Makeblocks) you will need are detailed thoroughly. The robot will be able to anticipate obstacle while capable of following a lined path on a floor surface (Delivering mail comes to my mind). This chapter is focused on sensors, motors, and mechanical construction. With sensors the authors take you through how to use infrared and ultrasonic capabilities. When using motors this chapter explains pulse width modulation (PWM) to control the speed of the robot. The Java code examples are quite straight forward and concise.

Chapter 6: Tea Station

Not a coffee drinker? but a Java fanboy well, this project is for all the tea lovers (including you) out there! This project is building a tea station to steep the perfect cup of tea. In this chapter the author discusses electronic scales (again) except ones having better precision due to tea leaves being extremely light in weight. The author goes on to discuss about temperature sensors that can determine how hot the tea should be when below the temperature of boiling water with very good accuracy. The author delves into serial (RS232 to TTL) communications with various vendors selling electronic scales (In chapter 2, USB was used). Learning this skill is invaluable because many older devices still use serial communications, so you can adapt your ideas with just about anything.

In this chapter the author really takes things to the next level compared to chapter 2 (brewing coffee), because he teaches you how to implement a snazzy JavaFX UI on a touchscreen device! Just like the chapter on brewing coffee the authors have an incredible depth of knowledge on teas and types of teas.

Chapter 7: Autonomous Drone

I’m sure you’ve heard a lot about the drone craze well this chapter will knock your socks off! The authors will be employing a quadcopter and the Raspberry Pi capable of flying autonomously. Don’t be afraid the drone in this project it will not hurt you. Interestingly, enough this chapter will use two WiFi adapters to be attached to the Raspberry Pi (Model B). One adapter is to talk to the drone itself and the other is used as a wireless access point (WAP) to remotely talk to the Raspberry Pi. In this chapter the author highlights an API called Autonomous4j by Mark Heckler. Mr. Heckler is also the technical reviewer of this book. I’ve actually seen the drone in action at a JavaOne conference where Mr. Heckler and Mr. Weaver conducted a live demonstration. The APIs discussed in this chapter are very easy to use for example the following are some of the Java methods:

  • takeoff() – Causes drone to start and take off.
  • goLeft/goRight(int speed) – Given the percent of speed to fly left/right (its left or right)
  • forward/backward(int speed) – Cause drone to go forward/backward given a percent of speed
  • goHome() – Drone flies back to where it lifted off from
  • land() – Land and stop.

Chapter 8: Retro Video Game Emulator

Whoa!? If you are an 80s or 90s kid who enjoyed arcades and game consoles (I know I did) then this chapter is about creating an Nintendo Entertainment System (NES) game console! Most of the parts from the bill of materials can be obtained from the popular electronics company Adafruit. The author teaches you how to build a game controller, attach a speaker, and attach a LCD touch display. This project will involve learning how to connecting GPIO pins to the Kippah board to control a touchscreen display. The author walks you through using a NES emulation Java library halfNES by Andrew Hoffman. As most of you know when dealing with emulators it isn’t legal to play game ROMs of popular games back in the day, unless you actually own the old game cartridge, so the author suggest heading over to a site having free games you can play. I’m sure if you own Mario Brothers you can get the game ROM and try it out. The author ends the chapter with more hacking tips such as overclocking your chip to increase the performance of your Pi. It’s a game so you need it to run fast!

Chapter 9: NightHacking RetroPi

After you’ve learned from chapter 8 on how to build a game console, this chapter will show you how to make a portable hand-held game device just like a Nintendo Game boy!  The author is thoughtful in discussing about the pros and cons on various 3D printers and existing DIY communities at large. This chapter points out all the necessary software to print parts for your hand-held game device. The author provides great illustrations to step you through creating a polished product.

Conclusion

This book has opened my eyes to innovative ideas using Java with the Raspberry Pi. The content is well organized and easy to follow. Often other DIY books have difficulty explaining the integration between hardware and software, but this book blends the two together elegantly. This book is very definitive in terms of the numerous topics, vendors, components, comparisons and implementation strategies. The authors hit on practically every topic relating to how to command and control (many types of) devices.

A good number of projects are very hands-on with an emphasis on the engineering side of things as opposed to the software side (solely a software developer). If you like to build cool gadgets and comfortable with the Java programming language I urge you to get this book.

My only issue (tiny) is the paperback book’s illustrations are in black and white (gray-scale) which can make it difficult to see things such as colored resistors in the Fritzing diagrams or JavaFX UIs (User Interfaces). I believe the PDF version might be in color, but I’ve not seen it yet (just a hunch). But, overall I give this book a two thumbs up. By far, this book is the most comprehensive book combining two great technologies with a plethora of amazing DIY projects to date.

Advertisement

Introduction by Example: JavaFX 8 Printing

I‘ve not blogged in awhile, and I miss sharing with others about all things JavaFX (My day job and family are likely excuses). For those who are new to this blog, I am the author of JavaFX 2 Introduction by Example (JIBE), co-author of Java 7 Recipes, and technical reviewer of the Pro JavaFX 2 books from Apress publishing. For those who already know me, I’d like to thank you for supporting me and the other authors by purchasing these books. More importantly, my hope is to reach out to  Java enthusiasts and share ideas.

The book JavaFX 2 Introduction by Example, was published in Nov. 2011 and many more APIs were added since then. During the writing of the book, I was working on the early editions of JavaFX 2.0 up until the announcement at JavaOne Oct. 2011. It was pretty crazy trying to update the book based on API changes as things were almost set in stone. I thought it was amazing how it even got out the door. However, I was pretty pleased. Some of you who have read the beginning of the book (JIBE) understand that the chapters of JIBE are also found in the book Java 7 Recipes (actually it is originally taken from Java 7 recipes). This little fact explains why the book, JavaFX 2 Introduction by Example, is reminiscent of recipe or cookbook style technical books. My intent was to help the reader get introduced quickly without a lot of tech blather. Instead of trying to convince people about the JavaFX platform, I’d rather demonstrate things with useful examples. I find it counter productive discussing  deep philosophical debates regarding why one particular technology is superior to the other (cheesy 80’s Highlander reference).

After the release of JavaFX 2.0, there came subsequent versions such as JavaFX 2.1, 2.2 and the upcoming release of JavaFX 8 (January 2014). In this blog entry, I will provide a recipe for the JavaFX 8’s Printing API. Similar to my book (JIBE), I will follow the same pattern as before where I present a problem, solution, code, and a “How it Works” section.

Declaimer: In this blog you will encounter Java Functional Interfaces using Lambda expressions. I will not be discussing them here, but will refer you to Oracle’s tutorials on Project Lambda .

Prerequisite software:

JDK 8 – https://jdk8.java.net/download.html

 

Problem

You want to create a JavaFX application that prints out a visited website.

Solution

Use the JavaFX 8 PrintJob and Printer APIs to print any JavaFX scene graph node. Also, use the WebView and WebEngine APIs to display a Website or Web page.

Instructions

Assuming you’ve compiled and have run the application, follow the instruction below:

  1. Enter website address or url into the text field.
  2. Hit the enter key
  3. After the page is loaded, click on the “Print” button
  4. Go to the printer to get the printed web page

Code

package org.carlfx;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.concurrent.Worker.State;
import javafx.print.*;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.transform.Scale;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 * Demo to use JavaFX 8 Printer API.
 *
 * @author cdea
 */
public class PrintDemo extends Application {
    @Override
    public void start(Stage primaryStage) {

        final TextField urlTextField = new TextField();
        final Button printButton = new Button("Print");
        final WebView webPage = new WebView();
        final WebEngine webEngine = webPage.getEngine();

        HBox hbox = new HBox();
        hbox.getChildren().addAll(urlTextField, printButton);
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(hbox);
        borderPane.setCenter(webPage);
        Scene scene = new Scene(borderPane, 300, 250);
        primaryStage.setTitle("Print Demo");
        primaryStage.setScene(scene);

        // print button pressed, page loaded
        final BooleanProperty printButtonClickedProperty = new SimpleBooleanProperty(false);
        final BooleanProperty pageLoadedProperty = new SimpleBooleanProperty(false);

        // when the a page is loaded and the button was pressed call the print() method.
        final BooleanProperty printActionProperty = new SimpleBooleanProperty(false);
        printActionProperty.bind(pageLoadedProperty.and(printButtonClickedProperty));

        // WebEngine updates flag when finished loading web page.
        webEngine.getLoadWorker()
                 .stateProperty()
                 .addListener( (ChangeListener) (obsValue, oldState, newState) -> {
                    if (newState == State.SUCCEEDED) {
                        pageLoadedProperty.set(true);
                    }
                 });

        // When user enters a url and hits the enter key.
        urlTextField.setOnAction( aEvent ->  {
            pageLoadedProperty.set(false);
            printButtonClickedProperty.set(false);
            webEngine.load(urlTextField.getText());
        });

        // When the user clicks the print button the webview node is printed
        printButton.setOnAction( aEvent -> {
            printButtonClickedProperty.set(true);
        });

        // Once the print action hears a true go print the WebView node.
        printActionProperty.addListener( (ChangeListener) (obsValue, oldState, newState) -> {
            if (newState) {
                print(webPage);
            }
        });

        primaryStage.show();

    }

    /** Scales the node based on the standard letter, portrait paper to be printed.
     * @param node The scene node to be printed.
     */
    public void print(final Node node) {
        Printer printer = Printer.getDefaultPrinter();
        PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
        double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
        double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
        node.getTransforms().add(new Scale(scaleX, scaleY));

        PrinterJob job = PrinterJob.createPrinterJob();
        if (job != null) {
            boolean success = job.printPage(node);
            if (success) {
                job.endJob();
            }
        }
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}
Print Demo using JavaFX 8

Print Demo using JavaFX 8

How it Works

The code begins by creating a TextField, a Button, and a WebView control to be placed into a BorderPane. When using the BorderPane layout, you will be able to place controls into the following regions: Top, Right, Left, Bottom, and Center.

Similar to a web browser, the text field allows the user to enter a website url. Once the url is entered, the user will hit the enter key to load the web page into the WebView node. When placing controls on any of the side regions, the BorderPane layout will take on the preferred height of any controls that are added. The center region will allow a node to take up the available space minus the remaining space taken up by the width and height of the bordering side regions. In other words, if the side regions contain no nodes (empty), a node in the center region has the opportunity to take all the available width and height space provided by its parent (Scene). Since the WebView node will occupy the center region, it will take all the available width and height (minus top region) when the web page is fully loaded. You’ll also notice scroll bars allowing the user to view pages larger than the current view port.

After laying out all the components for the UI, you will need to wire things up. Here you will simply create three boolean property
(javafx.beans.property.SimpleBooleanProperty) instances. The first property variable printButtonClickedProperty is a flag indicating when the print button was clicked. The second property pageLoadedProperty is a flag indicating that the web page was finished loading. Lastly, you will want to note the printActionProperty which binds the printButtonClickedProperty and the pageLoadedProperty by using the fluent API. As they evaluate, the printActionProperty will be true if both the printLoadedProperty and the printLoadedProperty are true values.

// print button pressed, page loaded
final BooleanProperty printButtonClickedProperty = new SimpleBooleanProperty(false);
final BooleanProperty pageLoadedProperty = new SimpleBooleanProperty(false);

// when the a page is loaded and the button was pressed call the print() method.
final BooleanProperty printActionProperty = new SimpleBooleanProperty(false);
printActionProperty.bind(pageLoadedProperty.and(printButtonClickedProperty));

Continuing the wiring up of the UI, I took an event driven approach where the handler code will respond to events and property changes. Starting with the WebView node, I attached handler code to the statePropery instance (ChangeListener) in order that the pageLoadedProperty will be set to true once the web page is loaded successfully.

  // WebEngine updates flag when finished loading web page.
  webEngine.getLoadWorker()
           .stateProperty()
           .addListener( (ChangeListener) (obsValue, oldState, newState) -> {
               if (newState == State.SUCCEEDED) {
                    pageLoadedProperty.set(true);
               }
           });

Next, you will see the text field’s ‘setOnAction‘ method containing handler code that resets the pageLoadedProperty and printButtonClickedProperty objects. Also, the code will initiate the loading of the page via the WebView‘s WebEngine load() method.


  // When user enters a url and hits the enter key.
  urlTextField.setOnAction( aEvent ->  {
     pageLoadedProperty.set(false);
     printButtonClickedProperty.set(false);
     webEngine.load(urlTextField.getText());
  });

After the TextField control’s action code is wired up, the print button will also need handler code to set the printButtonClickedProperty flag to true. Lastly, the printActionProperty property will need a ChangeListener to respond when its state evaluates to true. When this evaluates to true, my print() method is invoked.

        // When the user clicks the print button the webview node is printed
        printButton.setOnAction( aEvent -> {
            printButtonClickedProperty.set(true);
        });

        // Once the print action hears a true go print the WebView node.
        printActionProperty.addListener( (ChangeListener) (obsValue, oldState, newState) -> {
            if (newState) {
                print(webPage);
            }
        });

Finally, the print() method takes a JavaFX Node object to be printed. The Printer object has a method which returns the default printer your computer is set to. Before actually printing, we can derive a default page layout to scale the node before printing the node. If you don’t do this, only part of the web page will be printed. With the default printer obtained, the createPrinterJob() method is invoked to return a PrinterJob instance that does the actual printing. To print a JavaFX displayable type node, you simply invoke the PrinterJob object’s printPage() method by passing in the Node instance as a parameter.

    /** Scales the node based on the standard letter, portrait paper to be printed.
     * @param node The scene node to be printed.
     */
    public void print(final Node node) {
        Printer printer = Printer.getDefaultPrinter();
        PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
        double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
        double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
        node.getTransforms().add(new Scale(scaleX, scaleY));

        PrinterJob job = PrinterJob.createPrinterJob();
        if (job != null) {
            boolean success = job.printPage(node);
            if (success) {
                job.endJob();
            }
        }
    }

In conclusion, I find that the APIs are simpler to use compared to Java Swing/AWT APIs. I would like to mention that there are many features you can play around with since this blog entry only scratches the surface on the APIs currently available.

NOTE: JavaFX 8 printer API is still in the early stages and there are still outstanding issues (Jira issues).

Please visit to vote and help test functionality at https://javafx-jira.kenai.com

Outstanding Tickets: http://bit.ly/1dw7Vc8

I’ll be back…

Hey everyone!

I’m sorry to inform you that I will be taking a break from the JavaFX Game Tutorials to prepare for my upcoming presentation at the Montgomery county (Maryland) Java user group (http://www.mcjug.org) on July 18, 2012. If any of you Java fans are in town stop by between 6:00-8:00pm EST. My talk will be about an introduction to building JavaFX 2 enterprise applications using Grails.

I look forward to resuming where we left off in the JavaFX Game Tutorial series. 😉

Code well my friends!

Carl

JavaFX 2.0 Introduction by Example book

I recently finished writing a book on the new release of the JavaFX 2.0 SDK and it has already been placed on the shelves at a bookstore (Amazon) near you. The book will walk you through, step-by-step, giving you the ins and outs of JavaFX 2.0. When you encounter a chapter you will be presented recipes which will pose a problem (use case scenario) that will have an associated solution. After a proposed solution you will be shown an example source code listing and its display output after the program has been executed. Lastly you will be shown a section called “How it works” which will explain and discuss the examples and their details. To see more about this book, such as the source code and errata, please visit Apress Publishing (http://www.apress.com/9781430242574).

In this blog entry I also want to give you a sneak preview of a Java Webstart example of chapter 3 recipe 3-1 (JavaFX 2.0 MP3 Player). To launch the JavaFX MP3 player just jump down to Chapter 3 below.

Below is a brief overview of the chapters in the book:

Chapter 1: JavaFX Fundamentals

I begin by instructing you on how to get your environment set-up to rapidly develop rich internet applications using Java and JavaFX.

JavaFX Swiss army knife

After reading this chapter you will be able to answer questions such as:

  • How do I create GUI applications?
  • What is the Scene graph?
  • How do I display text onto the scene graph?
  • How do I incorporate UI controls into my application?
  • How do I bind expressions?
  • How do I draw shapes?
  • How do I generate a background process?
  • How do I associate keyboard sequences to applications?

Chapter 2: Graphics with JavaFX
In chapter 2 there are recipe examples which delve into JavaFX’s graphics and animation capabilities. I begin by explaining some of the basics of JavaFX’s Graphics such as rendering images and animating nodes. I then go on to more advanced topics such as animating with transitions, manipulating layouts, and enhancing nodes using JavaFX CSS.
The following picture, taken from Recipe 2-2, depicts an image viewer application with a custom news ticker control at the bottom.

Photo Viewer and News Ticker application

Photo Viewer and News Ticker application

Chapter 3: Media with JavaFX
Chapter 3 covers all things media related. Here I reveal JavaFX’s media APIs which allows you to integrate audio and video into your applications. I begin by showing you how to create a JavaFX MP3 player and a video player. Then I will walk you through the different ways to enhance the video player with additional features to control media actions and events, mark positions in a video, and synchronize animations.

The illustration below, taken from Recipe 3-1, depicts a JavaFX 2.0 MP3 player with a graphical visualization (using the AudioSpectrumListener API). Before launching the example you will need to know the requirements and instructions to run the demo example.

JavaFX 2.0 MP3 Player

JavaFX MP3 Player

Simple requirements and instructions to run the JavaFX 2.0 MP3 Player:

Requirements

  • Java 6 update 24 JRE or greater (Java 7 is preferred)
  • JavaFX 2.0 or greater (JavaFX 2.0.2 is preferred)
  • Windows XP SP 3 or greater. (I will update the jnlp as JavaFX becomes available on other OSes)

Instructions

  1. Click the Webstart launch button below.
  2. By using your file explorer on your host operating system “drag and drop” a music mp3 file onto the surface of the application.
  3. Use the controls to the bottom right of the application to pause, play, and stop the music.
  4. You may use your mouse to drag the application around your desktop.
  5. To close the application click on the ‘X’ in the upper right hand corner.

To launch the application click on the Java Webstart button below:

Demo JavaFX 2.0 MP3 Player

Chapter 4: JavaFX on the Web
In chapter 4 you will be able to take advantage of the interoperability between JavaFX and HTML5.

For starters I will cover how to embed JavaFX applications into a Web page. I then will demonstrate JavaFX’s powerful WebView and WebEngine APIs. Below are the recipe examples from chapter 4 which utilize the  WebView and WebEngine APIs:

  • Displaying HTML5 Content (animated analog clock application)
  • Loading data from a Web service (weather application)
  • Handling Web events
  • Storing and displaying data using an embedded database (RSS reader application)

Depicted below is an animated analog clock application, taken from Recipe 4-2, demonstrating the ability to render HTML5 content.

JavaFX 2.0 Analog Clock

JavaFX 2.0 Analog Clock (HTML5)

I assume you know the Java programming language and some web development concepts. I hope you will enjoy these examples which can be used freely in your own projects. I’ve tested the examples with the latest Java 7 update 2 and JavaFX 2.0.2 runtime and SDK. If you have any questions or comments feel free to ask them here or on my Twitter account @carldea .

Thanks!

Carl