How to Code a JavaFX FrontEnd for a Web-Service

At IDRSolutions we provide a web-service that converts PDF documents to HTML5 and we recently toyed with the idea of adding a GUI to our web service. In this tutorial I will be showing you how we went about tying our webservice to a JavaFX front-end.

Getting Started

To follow this tutorial, you will need :

  • An IDE capable of supporting web-services, we recommend NetBeans IDE 8.0.
  • Java 8 installed on your machine.
  • A basic understanding of JavaFX.
  • A free web-service account from here.

Setting up the WebService

Firstly, to be able to tie a GUI to our webservice we first need…. a webservice!

We will be creating ours in the NetBeans IDE, so lets get started.

  • Goto File > New Project > Select JavaFX > JavaFX Application >
  • Call it CloudConverter and make sure the JavaFX Platform is JDK 1.8
  • Where it says “Create Application Class”, change it from CloudConverter to CloudGUI.
  • Press Finish.
  • Now in the left-side Projects tab, expand CloudConverter project > expand Source Packages > expand cloudconverter package.
  • Right click cloudconverter package and select New > Web Service Client.
  • Select the WSDL URL radio button and paste your web-service WSDL URL into this text-field, in this tutorial we will use this WSDL URL :
    http://cloud.idrsolutions.com:8080/HTML_Page_Extraction/IDRConversionService?wsdl
  • Right click the cloudconverter package again and goto New > Java Class.
  • Give it the name IDRCloud and press Finish.

You have just setup your web-service! Your project should now look a little something like :

project

 

Tying our WebService Class to our JavaFX Class

Now that our web-service is up and running we can alter the code so it can be used with our JavaFX CloudGUI class. We will add some setters so we can set the username, password and other information from what the user enters into our GUI.

  • Replace the IDRCloud class code in our IDE with the one I’ve uploaded here.
  • Resolve any bad-imports.

Our IDRCloud class is now setup and it will handle all the file and information handling for our cloud converter. The next step is to tie our IDRCloud class to our CloudGUI class. Todo this we will create an IDRCloud object in the CloudGUI class.

First delete all unecersary code from your “start” method and instantiate our IDRCloud class as an Object. Your start method should look like this :

@Override
public void start(Stage primaryStage) {
    IDRCloud converter = new IDRCloud();
    /**
    * Finalise Containers and Stage.
    */
    StackPane root = new StackPane();
    Scene scene = new Scene(root, 300, 250);
 
    primaryStage.setTitle("CloudConverter GUI");
    primaryStage.setScene(scene);
    primaryStage.show();
}

By instantiating our IDRCloud class, we will have access to all the methods in IDRCloud and it will enable us to begin the connection to our Web Service. All future code will go after our converter object and before our finalisation of the containers and stage.

We now have a way to connect to our web service from our JavaFX GUI. So now we know how todo this and how to access the methods, we can can go ahead and code in the GUI Front-End for our Web Service.

Setting up the Web Service Front End (GUI)

So far in this tutorial, when we run the project we should get this great example of a useless GUI :
guiempty
However, by the end of this tutorial we should have something a little more user-friendly, like this :
guifinished

The order we’ll code our GUI is as follows. First we’ll code in the username and password text-fields. Then we’ll add our three buttons to select a PDF, Output Directory and a button to begin the conversion. Then we’ll code in our WebView object which will display the converted content after the conversion has finished. Lastly we’ll code in the File and Document chooser along with the Buttons Listeners.

Coding in the Username and Password Text Fields.

First let’s code in our User Name and Password text fields, this will be an area where the user can enter the email address they used to sign up to our web-service.

/**
* Setup TextFields.
*/
TextField userTF = new TextField();
userTF.setPromptText("Enter Username");
PasswordField passTF = new PasswordField();
passTF.setPromptText("Enter Password");

Coding in the Select File, Output Directory and Convert Buttons.

Secondly, we’ll code in our buttons, the Select File and Select Output buttons will be placed inside a HBox container which will make them display horizontally.

/**
* Setup Buttons.
*/
Button convertBtn = new Button("Convert");
 
HBox chooserHBox = new HBox();
Button selectFileBtn = new Button("Select PDF File");
Button selectOutputBtn = new Button("Select Output Directory");
chooserHBox.getChildren().addAll(selectFileBtn, selectOutputBtn);

Coding in the WebView Object and our File/Directory Choosers.

Thirdly, we need to add a WebView which will allow us to view our converted content after the conversion process has finished and the files have been sent to our output directory. And we will also need to add a couple of Choosers which will allows us to select a PDF file for conversion and an output directory for the converted files to be sent to.

/**
* Setup file Choosers.
*/
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select PDF File");
 
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle("Select Output Directory");
 
/**
* Setup WebView.
*/
WebView webview = new WebView();
 
<code>

Coding in the Action Listeners.

We need to add some listeners which can be tied to our interactive objects, these listeners will collect the information from the GUI that the user has entered, e.g username, password, pdf file and the output directory. This information will then be sent to our IDRCloud Object and will be used to connect to our Web Service and begin the Cloud Conversion.

/**
* Setup Listeners.
*/
convertBtn.setOnAction((ActionEvent) -> {
    converter.setUser(userTF.getText());
    converter.setPassword(passTF.getText());
    converter.execute();
    final URI uri = Paths.get(converter.getOutLoc() + converter.getFileName()).toAbsolutePath().toUri();
    webview.getEngine().load(uri.toString().substring(0, uri.toString().length()-4) + "//index.html");
});
selectFileBtn.setOnAction((ActionEvent) -> {
    File pdfFile = fileChooser.showOpenDialog(primaryStage);
    if(pdfFile!=null){
        converter.setInLoc(pdfFile.getParent() + "\\");
        converter.setFileName(pdfFile.getName());
    }
});
selectOutputBtn.setOnAction((ActionEvent) -> {
    File outputDir = dirChooser.showDialog(primaryStage);
    if(outputDir!=null){
        converter.setOutLoc(outputDir.getAbsolutePath() + "\\");
    }
});

Finally, Give it a Whirl!

Ok so we've finally finished our GUI, it's time to test it, if you followed this tutorial correctly, your start method code should look a little like the following :

@Override
public void start(Stage primaryStage) {
 
    /**
     * Setup Cloud Converter.
     */
    IDRCloud converter = new IDRCloud();
 
    /**
     * Setup Buttons.
     */
    Button convertBtn = new Button("Convert");
 
    HBox chooserHBox = new HBox();
    Button selectFileBtn = new Button("Select PDF File");
    Button selectOutputBtn = new Button("Select Output Directory");
    chooserHBox.getChildren().addAll(selectFileBtn, selectOutputBtn);
 
    /**
     * Setup TextFields.
     */
    TextField userTF = new TextField();
    userTF.setPromptText("Enter Username");
    PasswordField passTF = new PasswordField();
    passTF.setPromptText("Enter Password");
 
    /**
     * Setup file Choosers.
     */
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Select PDF File");
 
    DirectoryChooser dirChooser = new DirectoryChooser();
    dirChooser.setTitle("Select Output Directory");
 
    /**
    * Setup WebView.
    */
    WebView webview = new WebView();
 
    /**
     * Setup Listeners.
     */
    convertBtn.setOnAction((ActionEvent) -> {
        converter.setUser(userTF.getText());
        converter.setPassword(passTF.getText());
        converter.execute();
        final URI uri = Paths.get(converter.getOutLoc() + converter.getFileName()).toAbsolutePath().toUri();
        webview.getEngine().load(uri.toString().substring(0, uri.toString().length()-4) + "//index.html");
    });
    selectFileBtn.setOnAction((ActionEvent) -> {
        File pdfFile = fileChooser.showOpenDialog(primaryStage);
        if(pdfFile!=null){
            converter.setInLoc(pdfFile.getParent() + "\\");
            converter.setFileName(pdfFile.getName());
        }
    });
    selectOutputBtn.setOnAction((ActionEvent) -> {
        File outputDir = dirChooser.showDialog(primaryStage);
        if(outputDir!=null){
            converter.setOutLoc(outputDir.getAbsolutePath() + "\\");
        }
    });
 
    /**
     * Finalise Content.
     */
    VBox contentContainer = new VBox();
    contentContainer.getChildren().addAll(userTF, passTF,chooserHBox,convertBtn, webview);
 
    StackPane root = new StackPane();
    root.getChildren().add(contentContainer);
 
    Scene scene = new Scene(root, 500, 400);
 
    primaryStage.setTitle("Webservice Converter");
    primaryStage.setScene(scene);
    primaryStage.show();
}


We now have an interactive GUI where you can pass in the username and password you created when signing up to the webservice, if you missed signing up then click here to signup. You can select a PDF file to convert and an output directory for the HTML to be placed after conversion, your converted content will then be displayed in the web view object that we created.

Before Conversion :                                   After Conversion :
beforeGUI  guifinished

Thank you for reading this tutorial, I hope you enjoyed it and I hope you now understand how a JavaFX GUI can interact with a web-service. If you have any difficulties or questions then please post in the comments bellow. Thank you.

For the compiled jar and the code/classes we have written in this tutorial please see this zip:
WebServiceConverter.zip

You may find some of my other JavaFX articles of interest :

We also have a JavaFX PDF Viewer plugin for NetBeans which you can grab here.

This post is part of our “JavaFX article Index” series. In these articles, we aim to explore the world of Java and Javafx. Have a look through!

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

 

Ebook Page Link

The following two tabs change content below.
Nathan is a developer at IDRSolutions, focusing mainly on the development of HTML5 and Form support for the online PDF converter. He was a speaker and exhibitor at JavaOne 2013, co-presenting a session titled 'Lessons Learned from Using GlassFish with NetBeans". Nathan also enjoys writing technical blog-articles.

Related Posts:

Nathan

About Nathan Howard

Nathan is a developer at IDRSolutions, focusing mainly on the development of HTML5 and Form support for the online PDF converter. He was a speaker and exhibitor at JavaOne 2013, co-presenting a session titled 'Lessons Learned from Using GlassFish with NetBeans". Nathan also enjoys writing technical blog-articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>