Thursday, May 31, 2012

Communication between JavaFX and JavaScript inside WebView, using JSObject

The former articles demonstrate how to "Execute JavaScript in WebView from Java code" and "implement OnAlert EventHandler of WebEngine".

In order to call JavaFX from Javascript in WebView, we can create a JSObject in JavaFX, and then calling it's setMember() method to make it known to Javascript. After that, Javascript can call it's public methods and access it's public field.

Communication between JavaFX and JavaScript inside WebView


JavaFX code:
package javafxweb;

import java.net.URL;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXWeb extends Application {
    
    private Scene scene;
    MyBrowser myBrowser;
    
    Label labelFromJavascript;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        
        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 640, 480);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    class MyBrowser extends Region{
        
        HBox toolbar;
        VBox toolbox;
        
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        
        public MyBrowser(){
            
            final URL urlHello = getClass().getResource("hello.html");
            webEngine.load(urlHello.toExternalForm());
            
            webEngine.getLoadWorker().stateProperty().addListener(
                    new ChangeListener<State>(){
                        
                        @Override
                        public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
                            if(newState == State.SUCCEEDED){
                                JSObject window = (JSObject)webEngine.executeScript("window");
                                window.setMember("app", new JavaApplication());
                            }
                        }
                    });
            
            
            JSObject window = (JSObject)webEngine.executeScript("window");
            window.setMember("app", new JavaApplication());
            
            final TextField textField = new TextField ();
            textField.setPromptText("Hello! Who are?");
            
            Button buttonEnter = new Button("Enter");
            buttonEnter.setOnAction(new EventHandler<ActionEvent>(){
                
                @Override
                public void handle(ActionEvent arg0) {
                    webEngine.executeScript( " updateHello(' " + textField.getText() + " ') " );
                }
            });
            
            Button buttonClear = new Button("Clear");
            buttonClear.setOnAction(new EventHandler<ActionEvent>(){
                
                @Override
                public void handle(ActionEvent arg0) {
                    webEngine.executeScript( "clearHello()" );
                }
            });
            
            toolbar = new HBox();
            toolbar.setPadding(new Insets(10, 10, 10, 10));
            toolbar.setSpacing(10);
            toolbar.setStyle("-fx-background-color: #336699");
            toolbar.getChildren().addAll(textField, buttonEnter, buttonClear);
            
            toolbox = new VBox();
            labelFromJavascript = new Label();
            toolbox.getChildren().addAll(toolbar, labelFromJavascript);
            labelFromJavascript.setText("Wait");
            
            getChildren().add(toolbox);
            getChildren().add(webView);
            
        }
        
        @Override
        protected void layoutChildren(){
            double w = getWidth();
            double h = getHeight();
            double toolboxHeight = toolbox.prefHeight(w);
            layoutInArea(webView, 0, 0, w, h-toolboxHeight, 0, HPos.CENTER, VPos.CENTER);
            layoutInArea(toolbox, 0, h-toolboxHeight, w, toolboxHeight, 0, HPos.CENTER, VPos.CENTER);
        }
        
    }
    
    public class JavaApplication {
        public void callFromJavascript(String msg) {
            labelFromJavascript.setText("Click from Javascript: " + msg);
        }
    }
    
}


hello.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset=utf-8>
<title>Hello Java-Buddy!</title>
 
<script>

function updateHello(user){
  document.getElementById("helloprompt").innerHTML="Hello: " + user;
}
 
function clearHello(user){
  document.getElementById("helloprompt").innerHTML="Hello <a href='http://java-buddy.blogspot.com/'>Java-Buddy</a>";
}

function callJavaFX(){
    var msg = document.getElementById("textto").value;
    app.callFromJavascript(msg);
}
</script>
 
</head>
<body>
<img src="http://2.bp.blogspot.com/-Ol8pLJcc9oo/TnZY6R8YJ5I/AAAAAAAACSI/YDxcIHCZhy4/s150/duke_44x80.png"/>
<p id="helloprompt">Hello <a href="http://java-buddy.blogspot.com/">Java-Buddy</a></p>
<p><textarea id="textto"> </textarea></p>
<p><input type="button" value="Click to send message to Javascript" onclick="callJavaFX()"></p>
</body>
</html>


Wednesday, May 30, 2012

Embed WebView in FXML, to load OpenLayers with OpenStreetMap.

Last article demonstrate how to "Embed OpenLayers with OpenStreetMap in JavaFX WebView". This article demonstrate how to do it in FXML.

Embed WebView in FXML, to load OpenLayers with OpenStreetMap.


New a JavaFX FXML Application in NetBeans.

Copy openstreetmap.html from last article.

Create MyBrowser.java, extends Region.
package javafxml_web;

import java.net.URL;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class MyBrowser extends Region{
        HBox toolbar;

        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        
        public MyBrowser(){
            
            final URL urlGoogleMaps = getClass().getResource("openstreetmap.html");
            webEngine.load(urlGoogleMaps.toExternalForm());
            
            getChildren().add(webView);
        
        }
}

Modify Sample.fxml to add MyBrowser, and remove un-used elements.
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafxml_web.*?>

<AnchorPane id="AnchorPane" prefHeight="500" prefWidth="660" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxml_web.Sample">
    <children>
        <MyBrowser id="mybrowser" layoutX="10" layoutY="10" prefHeight="460" prefWidth="620" fx:id="mybrowser" />
    </children>
</AnchorPane>

Modify Sample.java to remove un-used code.
package javafxml_web;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Sample implements Initializable {
    
    @FXML
    private MyBrowser mybrowser;
    
    @FXML
    private void handleButtonAction(ActionEvent event) {

    }
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    
    
}

Embed OpenLayers with OpenStreetMap in JavaFX WebView

OpenLayers makes it easy to put a dynamic map in any web page. With OpenStreetMap, it's a free replacement of Google Maps. We can embed WebView loaded with OpenLayers in JavaFX to display map.

Embed OpenLayers with OpenStreetMap in JavaFX WebView


Create a HTML file, openstreetmap.html. Actually it's a normal web page HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8" />
 <script type="text/javascript" src="http://openlayers.org/api/2.11/OpenLayers.js"></script>
 <script type="text/javascript" >
  var myMap;
   
  function loadOpenLayers(){  
   
   myMap = new OpenLayers.Map("mymap", {});
    
   var wms = new OpenLayers.Layer.WMS(
    "OpenLayers WMS",
    "http://vmap0.tiles.osgeo.org/wms/vmap0",
    {layers: "basic"},
    {});
     
   myMap.addLayer(wms);
 
   myMap.setCenter(new OpenLayers.LonLat(-122.349243, 47.651743));
   myMap.zoomTo(6);   
  } 
  
 </script>
</head>
<body onload="loadOpenLayers();">
 <div id="mymap" style="width: 620px; height: 460px; border: 1px solid;">
 </div>
 
</body>
</html>


Java Code
package javafx_openstreetview;

import java.net.URL;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_OpenStreetView extends Application {
    
    private Scene scene;
    MyBrowser myBrowser;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        
        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 640, 480);
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    class MyBrowser extends Region{
        
        HBox toolbar;

        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        
        public MyBrowser(){
            
            final URL urlGoogleMaps = getClass().getResource("openstreetmap.html");
            webEngine.load(urlGoogleMaps.toExternalForm());
            
            getChildren().add(webView);
        
        }
    }
}


Related:
- Embed Google Maps in JavaFX WebView.
- Embed WebView in FXML, to load OpenLayers with OpenStreetMap.


Monday, May 28, 2012

Create PieChart using JavaFX and FXML


New a JavaFX FXML Application in NetBeans, modify Sample.fxml to add <PieChart> in FXML, and modify Sample.java to fill-in the ObservableList of PieChart.Data.

Sample.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.chart.*?>

<AnchorPane id="AnchorPane" prefHeight="520" prefWidth="520" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxml_charts.Sample">
    <children>
        <Button id="button1" layoutX="10" layoutY="10" text="Click to load PieChart 1" onAction="#handleButton1Action" fx:id="button1" />
        <Button id="button2" layoutX="10" layoutY="40" text="Click to load PieChart 2" onAction="#handleButton2Action" fx:id="button2" />
        <Button id="buttonclear" layoutX="10" layoutY="70" text="Clear PieChart" onAction="#handleButtonClearAction" fx:id="buttonclear" />
        
        <PieChart id="piechart" fx:id="piechart" layoutX="10" layoutY="110" />
        
    </children>
</AnchorPane>

Sample.java
package javafxml_charts;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.PieChart;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Sample implements Initializable {

    @FXML
    private PieChart piechart;
    
    @FXML
    private void handleButton1Action(ActionEvent event) {
        ObservableList<PieChart.Data> pieChartData = 
                FXCollections.observableArrayList(
                    new PieChart.Data("January", 100),
                    new PieChart.Data("February", 200),
                    new PieChart.Data("March", 50),
                    new PieChart.Data("April", 75),
                    new PieChart.Data("May", 110),
                    new PieChart.Data("June", 300),
                    new PieChart.Data("July", 111),
                    new PieChart.Data("August", 30),
                    new PieChart.Data("September", 75),
                    new PieChart.Data("October", 55),
                    new PieChart.Data("November", 225),
                    new PieChart.Data("December", 99));
        
        piechart.setTitle("Monthly Record");
        piechart.setData(pieChartData);
    }
    
    @FXML
    private void handleButton2Action(ActionEvent event) {
        ObservableList<PieChart.Data> pieChartData = 
                FXCollections.observableArrayList(
                    new PieChart.Data("Sunday", 30),
                    new PieChart.Data("Monday", 45),
                    new PieChart.Data("Tuesday", 70),
                    new PieChart.Data("Wednesday", 97),
                    new PieChart.Data("Thursday", 100),
                    new PieChart.Data("Friday", 80),
                    new PieChart.Data("Saturday", 10));
        
        piechart.setTitle("Weekly Record");
        piechart.setData(pieChartData);
    }
    
    @FXML
    private void handleButtonClearAction(ActionEvent event) {
        ObservableList<PieChart.Data> pieChartData = 
                FXCollections.observableArrayList();
        piechart.setTitle("");
        piechart.setData(pieChartData);
    }
        
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    
}


Sunday, May 27, 2012

JavaFX Scene Builder Docs Updated

JavaFX Scene Builder 1.0 Developer Release documentation has been updated.
  • Getting Started with JavaFX Scene Builder has been modified to use the latest JavaFX 2.2 development build and demonstrate the integration that is now available with the latest NetBeans IDE 7.2 development build. You can create your FXML layout file using the NetBean's New wizard and use the Scene Builder visual tool to continue designing the user interface for your JavaFX application. Simply drag and drop UI components to a work area,modify their properties, apply style sheets, and the FXML code for the layout is automatically generated in the background. The changes are immediately reflected with your project that is opened in the NetBeans IDE.
  • JavaFX Scene Builder User Guide has been modified to reflect the latest UI modifications made with build 38.
  • JavaFX Scene Builder Installation Guide to help you download, install, and start using JavaFX Scene Builder.

Related:
- NetBeans IDE 7.2 Beta Released
- Getting Started with JavaFX Scene Builder


Getting Started with JavaFX Scene Builder



JavaFX Scene Builder is a design tool for the JavaFX platform. It allows for the simple drag and drop of graphical user interface (GUI) components onto a JavaFX scene. As you build the scene, the FXML code for the designed application interface is automatically generated. This video will show you how to get started with the Scene Builder.

Related:
- JavaFX Scene Builder Docs Updated


NetBeans IDE 7.2 Beta Released



NetBeans IDE 7.2 Beta provides a significantly improved performance and coding experience, with new static code analysis capabilities in the Java Editor and smarter project scanning. The release also includes notable features such as integration with Scene Builder for visually creating JavaFX forms; support for multiple PHP frameworks; updated Groovy support; and many other enhancements in Java EE, Maven, C/C++ and the NetBeans Platform.

NetBeans IDE 7.2 Beta is available in English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese.

NetBeans IDE 7.2 Beta Release Information

Related:
- Getting Started with JavaFX Scene Builder
- JavaFX Scene Builder Docs Updated


Friday, May 25, 2012

Calculate the power of a number in Java

To calculate the result of "power of number" in Java, calling the method:

static double pow(double a, double b)

It returns the value of the first argument (a) raised to the power of the second argument (b).

Reference: java.lang.Math

PS. ^ operator in Java is Bitwise exclusive OR.


Thursday, May 24, 2012

Create TilePane using FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.image.*?>

<TilePane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml"
    prefHeight="200" prefWidth="300" >
        
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        <ImageView>
            <image>
                <Image url="http://goo.gl/kYEQl"/>        
            </image>
        </ImageView>
        
</TilePane>


Create TilePane using FXML


Related:
- Create TilePane using Java code
- TilePane in vertical


TilePane in vertical

TilePane in vertical


package javafx_tilepane;

import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        
        TilePane horizontalTile = new TilePane(Orientation.VERTICAL);
        
        horizontalTile.setHgap(8);
        horizontalTile.setPrefColumns(4);
            for (int i = 0; i < 20; i++) {
                horizontalTile.getChildren().add(new ImageView("http://goo.gl/kYEQl"));
            }

        primaryStage.setScene(new Scene(horizontalTile, 450, 450));
        primaryStage.show();
    }
}


Related:
- Create TilePane using Java code
- Create TilePane using FXML


Create TilePane using Java code

javafx.scene.layout.TilePane lays out its children in a grid of uniformly sized "tiles".

TilePane


package javafx_tilepane;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        
        TilePane horizontalTile = new TilePane();
        
        horizontalTile.setHgap(8);
        horizontalTile.setPrefColumns(4);
            for (int i = 0; i < 20; i++) {
                horizontalTile.getChildren().add(new ImageView("http://goo.gl/kYEQl"));
            }

        primaryStage.setScene(new Scene(horizontalTile, 450, 450));
        primaryStage.show();
    }
}


Related:
- TilePane in vertical
- Create TilePane using FXML


Create StackPane using FXML

javafx.scene.layout.StackPane lays out its children in a back-to-front stack.

The z-order of the children is defined by the order of the children list with the 0th child being the bottom and last child on top. If a border and/or padding have been set, the children will be layed out within those insets.

The stackpane will attempt to resize each child to fill its content area. If the child could not be sized to fill the stackpane (either because it was not resizable or its max size prevented it) then it will be aligned within the area using the alignment property, which defaults to Pos.CENTER.

StackPane


<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<StackPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml"
    prefHeight="200" prefWidth="400" >
        
        <Button text="Bottom Button" />
        <Button text="Button" />
        <Text text="Text"/>
        
</StackPane>


Compare to create StackPane using Java code.


Tuesday, May 22, 2012

Create AnchorPane using FXML

javafx.scene.layout.AnchorPane allows the edges of child nodes to be anchored to an offset from the anchorpane's edges. If the anchorpane has a border and/or padding set, the offsets will be measured from the inside edge of those insets.

Modify Sample.fxml in the last article "Create GridPane using FXML" to replace GridPane with AnchorPane.

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<AnchorPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml"
    prefHeight="200" prefWidth="400" >

        <Text text="java-Buddy" AnchorPane.topAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"/>
        <Label text="Who are you?" AnchorPane.topAnchor="25.0" AnchorPane.leftAnchor="0.0"/>
        <TextField id="textfield" fx:id="textfield" AnchorPane.topAnchor="25.0" AnchorPane.rightAnchor="0.0"/>
        <Button id="button"  text="Click Me!"
            onAction="#handleButtonAction" fx:id="button" 
            AnchorPane.topAnchor="50.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"/>
        <Label id="label" fx:id="label" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0"/>
        
</AnchorPane>


AnchorPane



Monday, May 21, 2012

Create FlowPane using FXML

javafx.scene.layout.FlowPane lays out its children in a flow that wraps at the flowpane's boundary.

Modify Sample.fxml in the last article "Create GridPane using FXML" to replace GridPane with FlowPane. Default orientation in "horizontal".

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<FlowPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml" 
    prefHeight="200" prefWidth="200">
        
        <Text text="java-Buddy"/>
        <Label text="Who are you?"/>
        <TextField id="textfield" fx:id="textfield"/>
        <Button id="button"  text="Click Me!" 
            onAction="#handleButtonAction" fx:id="button"/>
        <Label id="label" fx:id="label"/>

</FlowPane>

default FlowPane in horizontal


FlowPane with orientation in "vertical".
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<FlowPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml" 
    prefHeight="70" prefWidth="350" orientation="vertical">
        
        <Text text="java-Buddy"/>
        <Label text="Who are you?"/>
        <TextField id="textfield" fx:id="textfield"/>
        <Button id="button"  text="Click Me!" 
            onAction="#handleButtonAction" fx:id="button"/>
        <Label id="label" fx:id="label"/>

</FlowPane>


FlowPane in vertical


Sunday, May 20, 2012

Create BorderPane using FXML

javafx.scene.layout.BorderPane lays out children in top, left, right, bottom, and center positions.

By using FXML, we can change the visual view without touch the Java code.

BorderPane using FXML

Modify Sample.fxml in the last article "Create GridPane using FXML" to replace GridPane with BorderPane.

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<BorderPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml" 
    prefHeight="200" prefWidth="320">
        
    <top>
        <Text text="java-Buddy"/>
    </top>
    <left>
        <Label text="Who are you?"/>
    </left>
    <center>
        <TextField id="textfield" fx:id="textfield"/>
    </center>
    <right>
        <Button id="button"  text="Click Me!" 
            onAction="#handleButtonAction" fx:id="button"/>
    </right>
    <bottom>
        <Label id="label" fx:id="label"/>
    </bottom>

</BorderPane>



Create GridPane using FXML

javafx.scene.layout.GridPane lays out its children within a flexible grid of rows and columns.

GridPane using FXML


Modify Sample.fxml and Sample.java from the auto generated files described in the article "JavaFX FXML Application".

Sample.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.textfield.*?>

<GridPane fx:controller="javafxml.Sample" xmlns:fx="http://javafx.com/fxml" 
    prefHeight="200" prefWidth="320"
    alignment="center" hgap="10" vgap="10">

        <Text text="java-Buddy"
            GridPane.columnIndex="0" GridPane.rowIndex="0"
            GridPane.columnSpan="2"/>
        
        <Label text="Who are you?"
            GridPane.columnIndex="0" GridPane.rowIndex="1"/>
            
        <TextField id="textfield" fx:id="textfield"
            GridPane.columnIndex="1" GridPane.rowIndex="1"/>
 
        <Button id="button"  text="Click Me!" 
            onAction="#handleButtonAction" fx:id="button"
            GridPane.columnIndex="0" GridPane.rowIndex="2"/>
 
        <Label id="label" fx:id="label"
            GridPane.columnIndex="1" GridPane.rowIndex="2"/>
        

</GridPane>


Sample.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javafxml;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Sample implements Initializable {
    
    @FXML
    private Label label;
    @FXML
    private TextField textfield;
    
    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello  " + textfield.getText());
    }
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    
}


Related:
- Create BorderPane using FXML
- Create FlowPane using FXML
- Create AnchorPane using FXML


Saturday, May 19, 2012

Introduce JavaFX Scene Builder

JavaFX Scene Builder is a design tool that enables you to drag and drop graphical user interface (GUI) components onto a JavaFX scene. It can help you to quickly prototype interactive applications that connect GUI components to the application logic. It automatically generates the FXML source code as you define the GUI layout for your application.

Before you can use the JavaFX Scene Builder. You also need to install the NetBeans IDE 7.2 Beta, which is used in this tutorial. See the JavaFX Scene Builder Installation Guide for more details.

The Getting Started with JavaFX Scene Builder document presents the step-by-step creation of a simple issue-tracking application. It shows how quickly you can build the GUI for a JavaFX application by using JavaFX Scene Builder and connect it to the source code that handles the interaction between the data and the user interface.

Friday, May 18, 2012

JavaFX FXML Application


FXML is a scriptable, XML-based markup language for constructing Java object graphs. It provides a convenient alternative to constructing such graphs in procedural code, and is ideally suited to defining the user interface of a JavaFX application, since the hierarchical structure of an XML document closely parallels the structure of the JavaFX scene graph.

- To creates a JavaFX FXML-enabled application in a standard IDE project: Click File -> New Project... in NetBeans IDE.

- Select Categories of JavaFX, and Projects of JavaFX FXML Application, then click Next.


- Enter name and location of the project, then click Finish.


Three Files under Source Packages will be created:
  • Sample.fxml: The FXML source file to define the UI.
  • Sample.java: The controller file to handle user input of mouse and keyboard.
  • helloFXML.java: The main Java code.



Now, try to run the auto-generated JavaFX FXML Application.


Thursday, May 17, 2012

Preview HTMLEditor content in WebView

We can load content of HTMLEditor in WebView using loadContent() method of WebEngine.

Preview HTMLEditor content in WebView


package javafx_html;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.web.*;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final HTMLEditor htmlEditor = HTMLEditorBuilder.create()
                .prefHeight(200)
                .prefWidth(400)
                .build();

        final WebView webView = WebViewBuilder.create()
                .prefWidth(400)
                .build();
        
        final WebEngine webEngine = webView.getEngine();
        
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("noborder-scroll-pane");
        scrollPane.setContent(webView);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(180);
        
        Button buttonPreview = new Button("Preview");
        buttonPreview.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                webEngine.loadContent(htmlEditor.getHtmlText());
            }
        });

        VBox vBox = VBoxBuilder.create()
                .children(htmlEditor, scrollPane, buttonPreview)
                .build();
        
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
    
}


Related:
- Save and Load HTMLEditor in file

Wednesday, May 16, 2012

Load file to HTMLEditor

Last article explain how to "Read text file with JavaFX FileChooser". It's added in the code of previous article "Save HTMLEditor generated code in file", to add the function of loading file to HTMLEditor.

Load file to HTMLEditor


package javafx_html;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.HTMLEditorBuilder;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final HTMLEditor htmlEditor = HTMLEditorBuilder.create()
                .prefHeight(200)
                .prefWidth(400)
                .build();
        
        final TextArea htmlText = TextAreaBuilder.create()
                .prefWidth(400)
                .wrapText(true)
                .build();
        
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("noborder-scroll-pane");
        scrollPane.setContent(htmlText);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(180);
        
        Button buttonUpdate = new Button("Update");
        buttonUpdate.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                htmlText.setText(htmlEditor.getHtmlText());
            }
        });
        
        Button buttonSave = new Button("Save");
        buttonSave.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                String stringHtml = htmlEditor.getHtmlText();
                htmlText.setText(stringHtml);
                
                FileChooser fileChooser = new FileChooser();
                
                //Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("HTML files (*.html)", "*.html");
                fileChooser.getExtensionFilters().add(extFilter);
                
                //Show save file dialog
                File file = fileChooser.showSaveDialog(primaryStage);
                if(file != null){
                    SaveFile(stringHtml, file);
                }
            }
        });
        
        Button buttonLoad = new Button("Load");
        buttonLoad.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent arg0) {
                FileChooser fileChooser = new FileChooser();
                
                //Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("HTML files (*.html)", "*.html");
                fileChooser.getExtensionFilters().add(extFilter);
                
                //Show open file dialog
                File file = fileChooser.showOpenDialog(primaryStage);
                if(file != null){
                    String textRead = readFile(file);
                    htmlEditor.setHtmlText(textRead);
                    htmlText.setText(textRead);
                }
            }
            
        });
        
        HBox buttonBox =HBoxBuilder.create()
                .children(buttonUpdate, buttonSave, buttonLoad)
                .spacing(5)
                .build();

        VBox vBox = VBoxBuilder.create()
                .children(htmlEditor, htmlText, buttonBox)
                .build();
        
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
    
    private void SaveFile(String content, File file){
        try {
            FileWriter fileWriter = null;
            
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_HTMLeditor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private String readFile(File file){
        StringBuilder stringBuffer = new StringBuilder();
        BufferedReader bufferedReader = null;
        
        try {

            bufferedReader = new BufferedReader(new FileReader(file));
            
            String text;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaFX_HTMLeditor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_HTMLeditor.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_HTMLeditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
        
        return stringBuffer.toString();
    }
    
}


Related:
- Preview HTMLEditor content in WebView


Monday, May 14, 2012

Read text file with JavaFX FileChooser

Example to choose and read text file with JavaFX FileChooser.

choose and read text file with JavaFX FileChooser


package javafxfilechooser;

import java.io.*;
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.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        
        
        final TextArea textArea = TextAreaBuilder.create()
                .prefWidth(400)
                .wrapText(true)
                .build();
        
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("noborder-scroll-pane");
        scrollPane.setContent(textArea);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefWidth(400);
        scrollPane.setPrefHeight(180);
        
        Button buttonLoad = new Button("Load");
        buttonLoad.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent arg0) {
                FileChooser fileChooser = new FileChooser();
                
                //Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
                fileChooser.getExtensionFilters().add(extFilter);
                
                //Show save file dialog
                File file = fileChooser.showOpenDialog(primaryStage);
                if(file != null){
                    textArea.setText(readFile(file));
                }
            }
            
        });
        
        VBox vBox = VBoxBuilder.create()
                .children(buttonLoad, scrollPane)
                .build();
        
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
    
    private String readFile(File file){
        StringBuilder stringBuffer = new StringBuilder();
        BufferedReader bufferedReader = null;
        
        try {

            bufferedReader = new BufferedReader(new FileReader(file));
            
            String text;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaFX_OpenFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_OpenFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_OpenFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
        
        return stringBuffer.toString();
    }
}


Related:
- Save file with JavaFX FileChooser
- Use JavaFX FileChooser to open image file, and display on ImageView


Read text file using Java code

Example to read text from file:

package javafile;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class ReadStringFromFile {
    
    public static void main(String[] args) {
        
        File file = new File("C:/test/test.txt");
        
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        
        try {

            bufferedReader = new BufferedReader(new FileReader(file));
            
            String text;
            while ((text = bufferedReader.readLine()) != null) {
                stringBuffer.append(text);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                Logger.getLogger(ReadStringFromFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
                
        System.out.println(stringBuffer);
                
    }
    
}


Next:
- Read text file with JavaFX FileChooser


Sunday, May 13, 2012

Save HTMLEditor generated code in file

With the help of JavaFX FileChooser to save file, the HTMLEditor generated code can be saved using FileChooser SaveDialog.



The saved file opened in browser:
The saved file opened in browser


package javafx_html;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.HTMLEditorBuilder;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final HTMLEditor htmlEditor = HTMLEditorBuilder.create()
                .prefHeight(200)
                .prefWidth(400)
                .build();
        
        final TextArea htmlText = TextAreaBuilder.create()
                .prefWidth(400)
                .wrapText(true)
                .build();
        
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("noborder-scroll-pane");
        scrollPane.setContent(htmlText);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(180);
        
        Button buttonUpdate = new Button("Update");
        buttonUpdate.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                htmlText.setText(htmlEditor.getHtmlText());
            }
        });
        
        Button buttonSave = new Button("Save");
        buttonSave.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                String stringHtml = htmlEditor.getHtmlText();
                htmlText.setText(stringHtml);
                
                FileChooser fileChooser = new FileChooser();
                
                //Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("HTML files (*.html)", "*.html");
                fileChooser.getExtensionFilters().add(extFilter);
                
                //Show save file dialog
                File file = fileChooser.showSaveDialog(primaryStage);
                if(file != null){
                    SaveFile(stringHtml, file);
                }
            }
        });
        
        HBox buttonBox =HBoxBuilder.create()
                .children(buttonUpdate, buttonSave)
                .spacing(5)
                .build();

        VBox vBox = VBoxBuilder.create()
                .children(htmlEditor, htmlText, buttonBox)
                .build();
        
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
    
    private void SaveFile(String content, File file){
        try {
            FileWriter fileWriter = null;
            
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_HTMLeditor.class.getName()).log(Level.SEVERE, null, ex);
        }

         
    }
}


Next:
- Load file to HTMLEditor


Saturday, May 12, 2012

Javadoc not found in Netbeans for JavaFX


It's supposed that you can view the Javadoc for any of the library's class in Netbeans Source Editor. But somebody, include me, cannot view the Javadoc for JavaFX elements because Javadoc not found!


To include JavaFX Javadoc:
- Click Tools -> Java Platforms in Netbeans menu.

- Select your JavaFX Platform in Platforms box on left, click to enable JavaFX tab, Browse...to include JavaFX Javadoc folder.


- Close.

Now you should be able to view more in Javadoc while you are writing.


Save file with JavaFX FileChooser

javafx.stage.FileChooser provides support for standard file dialogs. The showSaveDialog(Window ownerWindow) method shows a new file save dialog. The method doesn't return until the displayed file save dialog is dismissed. The return value specifies the file chosen by the user or null if no selection has been made. If the owner window for the file dialog is set, input to all windows in the dialog's owner chain is blocked while the file dialog is being shown.

Example of saving file with JavaFX FileChooser:

Save file with JavaFX FileChooser


package javafx_text;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final String Santa_Claus_Is_Coming_To_Town =
                "You better watch out\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He's making a list\n"
                + "And checking it twice;\n"
                + "Gonna find out Who's naughty and nice\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He sees you when you're sleeping\n"
                + "He knows when you're awake\n"
                + "He knows if you've been bad or good\n"
                + "So be good for goodness sake!\n"
                + "\n"
                + "O! You better watch out!\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "Santa Claus is coming to town\n";
        
        Text textSong = TextBuilder.create()
                .text(Santa_Claus_Is_Coming_To_Town)
                .build();                
        
        Button buttonSave = ButtonBuilder.create()
                .text("Save")
                .build();
        
        buttonSave.setOnAction(new EventHandler<ActionEvent>() {
 
          @Override
          public void handle(ActionEvent event) {
              FileChooser fileChooser = new FileChooser();
 
              //Set extension filter
              FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
              fileChooser.getExtensionFilters().add(extFilter);
             
              //Show save file dialog
              File file = fileChooser.showSaveDialog(primaryStage);
             
              if(file != null){
                  SaveFile(Santa_Claus_Is_Coming_To_Town, file);
              }
          }
      });
        
        VBox vBox = VBoxBuilder.create()
                .children(textSong, buttonSave)
                .build();
                
        root.getChildren().add(vBox);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();

    }
    
    private void SaveFile(String content, File file){
        try {
            FileWriter fileWriter = null;
            
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_Text.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
}


Related:
- Read text file with JavaFX FileChooser
Save TextArea to file, using FileChooser

Write String to File using Java

It's a simple example to write String to text file using Java code. Please note that you need the right to write in the target file.

package javafile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        FileWriter fileWriter = null;
        try {
            String content = "Hello! Java-Buddy :)";
            File newTextFile = new File("C:/test/test.txt");
            fileWriter = new FileWriter(newTextFile);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


Related:
- Save file with JavaFX FileChooser


Friday, May 11, 2012

Obtain content of HTMLEditor

We can call getHtmlText() method of HTMLEditor object to obtain the content.

Example:
Obtain content of HTMLEditor


package javafx_html;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.HTMLEditorBuilder;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final HTMLEditor htmlEditor = HTMLEditorBuilder.create()
                .prefHeight(200)
                .prefWidth(400)
                .build();
        
        final TextArea htmlText = TextAreaBuilder.create()
                .prefWidth(400)
                .wrapText(true)
                .build();
        
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("noborder-scroll-pane");
        scrollPane.setContent(htmlText);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(180);
        
        Button buttonUpdate = new Button("Update");
        buttonUpdate.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent t) {
                htmlText.setText(htmlEditor.getHtmlText());
            }
        });

        VBox vBox = VBoxBuilder.create()
                .children(htmlEditor, htmlText, buttonUpdate)
                .build();
        
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Next:
- Save HTMLEditor generated code in file


Create your own HTML Editor in JavaFX2.1

In JavaFX 2.1, the class javafx.scene.web.HTMLEditor is a control that allows for users to edit text, and apply styling to this text. The underlying data model is HTML, although this is not shown visually to the end-user.

Example:
HTMLEditor in JavaFX2.1


package javafx_html;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        final HTMLEditor htmlEditor = new HTMLEditor();

        Group myGroup = GroupBuilder.create()
                .children(htmlEditor)
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Next: - Obtain content of HTMLEditor

Monday, May 7, 2012

JavaFX Binding, sync between UI component - display slider property

Last article we have a stand alone slider only. It's modified to bind with a Text, such that the text will be updated when the slider value changed.



package javafxui;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Slider extends Application {
    
    int defaultSliderValue = 10;
    IntegerProperty sliderValue = new SimpleIntegerProperty(defaultSliderValue);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();

        Slider slider = SliderBuilder.create()
                .layoutX(50)
                .layoutY(50)
                .prefWidth(400)
                .min(0)
                .max(100)
                .majorTickUnit(20)
                .minorTickCount(3)
                .showTickMarks(true)
                .showTickLabels(true)
                .tooltip(new Tooltip("Slider Tooltip"))
                .build();
        
        Text slidertext = TextBuilder.create()
                .layoutX(50)
                .layoutY(100)
                .fill(Color.RED)
                .font(Font.font("SansSerif", FontWeight.BOLD, 20))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(slider, slidertext)
                .build();
        
        root.getChildren().add(myGroup);
        
        slider.valueProperty().bindBidirectional(sliderValue);
        slidertext.textProperty().bind(sliderValue.asString());
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


JavaFX: Create Slider using SliderBuilder

Create Slider using SliderBuilder


package javafxui;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();

        Slider slider = SliderBuilder.create()
                .layoutX(50)
                .layoutY(50)
                .prefWidth(400)
                .min(0)
                .max(100)
                .majorTickUnit(20)
                .minorTickCount(3)
                .showTickMarks(true)
                .showTickLabels(true)
                .value(10)
                .tooltip(new Tooltip("Slider Tooltip"))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(slider)
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Next:
- JavaFX Binding, sync between UI component - display slider property

Sunday, May 6, 2012

Create ImageView using JavaFX ImageViewBuilder, load image from internet.

Create ImageView using ImageViewBuilder



package javafximage;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.ImageViewBuilder;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
                
        String imageSource = "http://goo.gl/kYEQl";
        
        ImageView imageView = ImageViewBuilder.create()
                .image(new Image(imageSource))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(imageView)
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Saturday, May 5, 2012

Create text with TranslateTransition animation effect

Example:


package javafx_text;

import javafx.animation.Interpolator;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.animation.TranslateTransitionBuilder;
import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.stage.Stage;
import javafx.util.Duration;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        String Santa_Claus_Is_Coming_To_Town =
                "You better watch out\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He's making a list\n"
                + "And checking it twice;\n"
                + "Gonna find out Who's naughty and nice\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He sees you when you're sleeping\n"
                + "He knows when you're awake\n"
                + "He knows if you've been bad or good\n"
                + "So be good for goodness sake!\n"
                + "\n"
                + "O! You better watch out!\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "Santa Claus is coming to town\n";
        
        Text textSong = TextBuilder.create()
                .text(Santa_Claus_Is_Coming_To_Town)
                .layoutX(50)
                .textOrigin(VPos.TOP)
                .textAlignment(TextAlignment.JUSTIFY)
                .fill(Color.BLUE)
                .font(Font.font("SansSerif", FontPosture.ITALIC, 18))
                .build();
        
        TranslateTransition translateTransition = TranslateTransitionBuilder.create()
                .node(textSong)
                .fromY(500)
                .toY(-500)
                .duration(new Duration(10000))
                .interpolator(Interpolator.LINEAR)
                .cycleCount(Timeline.INDEFINITE)
                .build();
                
        
        Group myGroup = GroupBuilder.create()
                .children(textSong)
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
        
        translateTransition.play();
    }
}


Friday, May 4, 2012

JavaFX - Create ScrollPane using ScrollPaneBuilder

Create ScrollPane using ScrollPaneBuilder


package javafx_text;

import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPaneBuilder;
import javafx.scene.paint.Color;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.*;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        String Santa_Claus_Is_Coming_To_Town =
                "You better watch out\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He's making a list\n"
                + "And checking it twice;\n"
                + "Gonna find out Who's naughty and nice\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He sees you when you're sleeping\n"
                + "He knows when you're awake\n"
                + "He knows if you've been bad or good\n"
                + "So be good for goodness sake!\n"
                + "\n"
                + "O! You better watch out!\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "Santa Claus is coming to town\n";
        
        Text textSong = TextBuilder.create()
                .text(Santa_Claus_Is_Coming_To_Town)
                .layoutX(50)
                .textOrigin(VPos.TOP)
                .textAlignment(TextAlignment.JUSTIFY)
                .fill(Color.BLUE)
                .font(Font.font("SansSerif", FontPosture.ITALIC, 18))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(
                    ScrollPaneBuilder.create()
                        .prefWidth(500)
                        .prefHeight(100)
                        .content(textSong)
                        .build()
                )
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


JavaFX - using GroupBuilder to create clip area

With clip:

package javafx_text;

import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.*;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        String Santa_Claus_Is_Coming_To_Town =
                "You better watch out\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He's making a list\n"
                + "And checking it twice;\n"
                + "Gonna find out Who's naughty and nice\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He sees you when you're sleeping\n"
                + "He knows when you're awake\n"
                + "He knows if you've been bad or good\n"
                + "So be good for goodness sake!\n"
                + "\n"
                + "O! You better watch out!\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "Santa Claus is coming to town\n";
        
        Text textSong = TextBuilder.create()
                .text(Santa_Claus_Is_Coming_To_Town)
                .layoutX(50)
                .textOrigin(VPos.TOP)
                .textAlignment(TextAlignment.JUSTIFY)
                .fill(Color.BLUE)
                .font(Font.font("SansSerif", FontPosture.ITALIC, 18))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(textSong)
                .clip(RectangleBuilder.create()
                        .width(500)
                        .height(100)
                        .build()
                )
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Without clip:

package javafx_text;

import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.*;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        String Santa_Claus_Is_Coming_To_Town =
                "You better watch out\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He's making a list\n"
                + "And checking it twice;\n"
                + "Gonna find out Who's naughty and nice\n"
                + "Santa Claus is coming to town\n"
                + "\n"
                + "He sees you when you're sleeping\n"
                + "He knows when you're awake\n"
                + "He knows if you've been bad or good\n"
                + "So be good for goodness sake!\n"
                + "\n"
                + "O! You better watch out!\n"
                + "You better not cry\n"
                + "Better not pout\n"
                + "I'm telling you why\n"
                + "Santa Claus is coming to town\n"
                + "Santa Claus is coming to town\n";
        
        Text textSong = TextBuilder.create()
                .text(Santa_Claus_Is_Coming_To_Town)
                .layoutX(50)
                .textOrigin(VPos.TOP)
                .textAlignment(TextAlignment.JUSTIFY)
                .fill(Color.BLUE)
                .font(Font.font("SansSerif", FontPosture.ITALIC, 18))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(textSong)
                .build();
        
        root.getChildren().add(myGroup);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


JavaFX TextBuilder with properties

JavaFX TextBuilder with properties


package javafx_text;

import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        
        String stringHello = "Hello, Java Buddy! \n"
                + "http://java-buddy.blogspot.com/";
        
        Text textHello = TextBuilder.create()
                .text(stringHello)
                .layoutX(50)
                .textOrigin(VPos.TOP)
                .textAlignment(TextAlignment.RIGHT)
                .fill(Color.BLUE)
                .font(Font.font("SansSerif", FontPosture.ITALIC, 28))
                .build();
        
        root.getChildren().add(textHello);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


Create text using javafx.scene.text.TextBuilder

Example to create text using TextBuilder.create():

package javafx_text;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        StackPane root = new StackPane();
        
        Text textHello = TextBuilder.create().text("Hello, Java Buddy!").build();
        
        root.getChildren().add(textHello);
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


create text using TextBuilder.create()


Do more with TextBuilder:
- JavaFX TextBuilder with properties