Wednesday, July 31, 2013

JavaFX Support in NetBeans IDE

JavaFX Support in NetBeans IDE

This screencast demonstrates JavaFX-related features that are implemented in NetBeans IDE 7.4 Beta, including the JavaFX runtime classpath, the alignment of JavaFX and Java SE projects and the JavaFX Maven project template.

Tuesday, July 30, 2013

JavaFX example: create new window at run-time

JavaFX example to create new window at run-time:

JavaFX example: create new window at run-time
JavaFX example: create new window at run-time
In action:



package javafx_newwindow;

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.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_NewWindow extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("New a Window");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Stage newStage = new Stage();
                Group newRoot = new Group();
                Scene scene = new Scene(newRoot, 300, 200);
                newStage.setScene(scene);
                newStage.show();
                
                VBox vBox = new VBox();
                
                Label newLabel = new Label();
                newLabel.setText(newStage.toString());
                
                Button btnClose = new Button("Close");
                btnClose.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent t) {
                        newStage.close();
                    }
                });
                
                vBox.getChildren().addAll(newLabel, btnClose);
                newRoot.getChildren().add(vBox);
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Friday, July 26, 2013

Another example to embed Open Weather Map in JavaFX WebView

It's another example to embed Open Weather Map in JavaFX WebView, with overlay.

Another example to embed Open Weather Map in JavaFX WebView
Another example to embed Open Weather Map in JavaFX WebView

Create HTML file, tiles.html, to load OpenWeatherMap in webpage.

tiles.html
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <style type="text/css">
            #map {
                width: 100%;
                height: 100%;
                border: 0px;
                padding: 0px;
                position: absolute;
            }

            body {
                border: 0px;
                margin: 0px;
                padding: 0px;
                height: 100%;
                font-family: sans-serif;
            }

            #links {
                background: #575757;
                color: white;
                z-index:1000;
                width: 33%;
                font-size: 1em;
                text-align: left;
                position: relative;
                top: 0.5em;
                left: 2.5em;
                padding: 5px;
                width: 33%;
                /* for IE */
                filter:alpha(opacity=90);
                /* CSS3 standard */
                opacity:0.9;
                border-radius: 4px;
            }

            .olControlAttribution {
                padding: 5px;
                z-index: 1000;
                bottom: 0.2em !important;
                overflow: hidden;
                background: #575757;
                color: white;
                width: 33%;
                font-size: 1em !important;
                text-align: right;
                /* for IE */
                filter:alpha(opacity=90);
                /* CSS3 standard */
                opacity:0.9;
                border-radius: 4px;
            }

            a:link, a:visited, a:hover, a:active {
                /*color: #00008a;*/
                color: #9e9eff;
            }
        </style>
        <script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
        <script src="http://openlayers.org/api/OpenLayers.js"></script>
        <script type="text/javascript">

            function init()
            {
                var args = OpenLayers.Util.getParameters();
                var layer_name = "temp";
                var lat = 0;
                var lon = 0;
                var zoom = 2;
                var opacity = 0.5;

                var map = new OpenLayers.Map("map",
                        {
                            units: 'm',
                            projection: "EPSG:900913",
                            displayProjection: new OpenLayers.Projection("EPSG:4326")
                        });

                var osm = new OpenLayers.Layer.XYZ(
                        "osm",
                        "http://${s}.tile.openweathermap.org/map/osm/${z}/${x}/${y}.png",
                        {
                            numZoomLevels: 18,
                            sphericalMercator: true
                        }
                );


                var mapnik = new OpenLayers.Layer.OSM();

                var opencyclemap = new OpenLayers.Layer.XYZ(
                        "opencyclemap",
                        "http://a.tile3.opencyclemap.org/landscape/${z}/${x}/${y}.png",
                        {
                            numZoomLevels: 18,
                            sphericalMercator: true
                        }
                );

                var layer = new OpenLayers.Layer.XYZ(
                        "layer " + layer_name,
                        "http://${s}.tile.openweathermap.org/map/" + layer_name + "/${z}/${x}/${y}.png",
                        //"http://wind.openweathermap.org/map/"+layer_name+"/${z}/${x}/${y}.png",
                                {
                                    //   numZoomLevels: 19, 
                                    isBaseLayer: false,
                                    opacity: opacity,
                                    sphericalMercator: true

                                }
                        );

                        var centre = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"),
                                new OpenLayers.Projection("EPSG:900913"));
                        map.addLayers([mapnik, osm, opencyclemap, layer]);
                        map.setCenter(centre, zoom);
                        var ls = new OpenLayers.Control.LayerSwitcher({'ascending': false});
                        map.addControl(ls);

                        map.events.register("mousemove", map, function(e) {
                            var position = map.getLonLatFromViewPortPx(e.xy).transform(new OpenLayers.Projection("EPSG:900913"),
                                    new OpenLayers.Projection("EPSG:4326"));

                            $("#mouseposition").html("Lat: " + Math.round(position.lat * 100) / 100 + " Lon: " + Math.round(position.lon * 100) / 100 +
                                    ' zoom: ' + map.getZoom());
                        });

                    }

        </script>

    </head>

    <body onload="init()">
        <div id="map" style='width: 500; height: 500'></div>
        <div id="links">
            <div unselectable="on" class="olControlAttribution olControlNoSelect"></div>
            <div id="mouseposition">Lat Lng</div>
        </div>
    </body>

    <script type="text/javascript">
            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-31601618-1']);
            _gaq.push(['_setDomainName', 'openweathermap.org']);
            _gaq.push(['_trackPageview']);
            (function() {
                var ga = document.createElement('script');
                ga.type = 'text/javascript';
                ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(ga, s);
            })();
    </script>
</html>


Java code to load the tiles.html in JavaFX WebView.
package javafx_openweathermap;

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_OpenWeatherMap extends Application {

    private Scene scene;
    MyBrowser myBrowser;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");

        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 500, 500);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    class MyBrowser extends Region {

        HBox toolbar;
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        public MyBrowser() {
            
            final URL urlWeatherMaps = getClass().getResource("tiles.html");
            webEngine.load(urlWeatherMaps.toExternalForm());

            getChildren().add(webView);

        }
    }
}


Thursday, July 25, 2013

Embed OpenWeatherMap in JavaFX WebView

OpenWeatherMap provide Javascript library to let developer load OpenWeatherMap in web page. So we can easy embed OpenWeatherMap in WebView of JavaFX.

Embed OpenWeatherMap in JavaFX WebView
Embed OpenWeatherMap in JavaFX WebView
Create HTML file, OpenWeatherMap.html, to load OpenWeatherMap in webpage. Copy the example from OpenWeatherMap tutorial for web developers.

OpenWeatherMap.html
<html>
<head>
<title>Open Weather Map</title>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script src="http://openweathermap.org/js/OWM.OpenLayers.1.3.4.js" ></script>
</head>
<body  onload="init()">
<div id="basicMap"></div>
</body>

<script type="text/javascript">
function init() {
 //Center of map
 var lat = 7486473; 
 var lon = 4193332;
 var lonlat = new OpenLayers.LonLat(lon, lat);
        var map = new OpenLayers.Map("basicMap");
 // Create overlays
 //  OSM
        var mapnik = new OpenLayers.Layer.OSM();
 // Stations
 var stations = new OpenLayers.Layer.Vector.OWMStations("Stations");
 // Current weather
 var city = new OpenLayers.Layer.Vector.OWMWeather("Weather");
 //Addind maps
 map.addLayers([mapnik, stations, city]);
 map.setCenter( lonlat, 10 );
}
</script>
</html>


Java code to load the OpenWeatherMap.html in JavaFX WebView.
package javafx_openweathermap;

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_OpenWeatherMap extends Application {

    private Scene scene;
    MyBrowser myBrowser;

    @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();
    }

    public static void main(String[] args) {
        launch(args);
    }

    class MyBrowser extends Region {

        HBox toolbar;
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        public MyBrowser() {

            final URL urlGoogleMaps = getClass().getResource("OpenWeatherMap.html");
            webEngine.load(urlGoogleMaps.toExternalForm());

            getChildren().add(webView);

        }
    }
}


Wednesday, July 24, 2013

Parse JSON with Java SE and java-json, to search weather data from OpenWeatherMap

OpenWeatherMap provide APIs to search weather data in JSON, XML or HTML format. This example demonstrate how to parse JSON from OpenWeatherMap to search weather of London, UK.

Before we can use java-json in our project, follow the instruction to add JAR in NetBeans.

Example code:

package java_openweathermap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

    static final String URL_OpenWeatherMap_weather_London_uk =
            "http://api.openweathermap.org/data/2.5/weather?q=London,uk";

    public static void main(String[] args) {
        
        String result = "";
        
        try {
            URL url_weather = new URL(URL_OpenWeatherMap_weather_London_uk);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url_weather.openConnection();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                InputStreamReader inputStreamReader =
                    new InputStreamReader(httpURLConnection.getInputStream());
                BufferedReader bufferedReader =
                    new BufferedReader(inputStreamReader, 8192);
                String line = null;
                while((line = bufferedReader.readLine()) != null){
                    result += line;
                }
                
                bufferedReader.close();
                
                String weatherResult = ParseResult(result);
                
                System.out.println(weatherResult);

            } else {
                System.out.println("Error in httpURLConnection.getResponseCode()!!!");
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static private String ParseResult(String json) throws JSONException{
        
        String parsedResult = "";
     
        JSONObject jsonObject = new JSONObject(json);

        parsedResult += "Number of object = " + jsonObject.length() + "\n\n";
     
        //"coord"
        JSONObject JSONObject_coord = jsonObject.getJSONObject("coord");
        Double result_lon = JSONObject_coord.getDouble("lon");
        Double result_lat = JSONObject_coord.getDouble("lat");
     
        //"sys"
        JSONObject JSONObject_sys = jsonObject.getJSONObject("sys");
        String result_country = JSONObject_sys.getString("country");
        int result_sunrise = JSONObject_sys.getInt("sunrise");
        int result_sunset = JSONObject_sys.getInt("sunset");
        
        //"weather"
        String result_weather;
        JSONArray JSONArray_weather = jsonObject.getJSONArray("weather");
        if(JSONArray_weather.length() > 0){
            JSONObject JSONObject_weather = JSONArray_weather.getJSONObject(0);
            int result_id = JSONObject_weather.getInt("id");
            String result_main = JSONObject_weather.getString("main");
            String result_description = JSONObject_weather.getString("description");
            String result_icon = JSONObject_weather.getString("icon");
        
            result_weather = "weather\tid: " + result_id +"\tmain: " + result_main + "\tdescription: " + result_description + "\ticon: " + result_icon;
        }else{
            result_weather = "weather empty!";
        }
        
        //"base"
        String result_base = jsonObject.getString("base");
        
        //"main"
        JSONObject JSONObject_main = jsonObject.getJSONObject("main");
        Double result_temp = JSONObject_main.getDouble("temp");
        Double result_pressure = JSONObject_main.getDouble("pressure");
        Double result_humidity = JSONObject_main.getDouble("humidity");
        Double result_temp_min = JSONObject_main.getDouble("temp_min");
        Double result_temp_max = JSONObject_main.getDouble("temp_max");
        
        //"wind"
        JSONObject JSONObject_wind = jsonObject.getJSONObject("wind");
        Double result_speed = JSONObject_wind.getDouble("speed");
        //Double result_gust = JSONObject_wind.getDouble("gust");
        Double result_deg = JSONObject_wind.getDouble("deg");
        String result_wind = "wind\tspeed: " + result_speed + "\tdeg: " + result_deg;
        
        //"clouds"
        JSONObject JSONObject_clouds = jsonObject.getJSONObject("clouds");
        int result_all = JSONObject_clouds.getInt("all");
        
        //"dt"
        int result_dt = jsonObject.getInt("dt");
        
        //"id"
        int result_id = jsonObject.getInt("id");
        
        //"name"
        String result_name = jsonObject.getString("name");
        
        //"cod"
        int result_cod = jsonObject.getInt("cod");
        
        return 
            "coord\tlon: " + result_lon + "\tlat: " + result_lat + "\n" +
            "sys\tcountry: " + result_country + "\tsunrise: " + result_sunrise + "\tsunset: " + result_sunset + "\n" +
            result_weather + "\n"+
            "base: " + result_base + "\n" +
            "main\ttemp: " + result_temp + "\thumidity: " + result_humidity + "\tpressure: " + result_pressure + "\ttemp_min: " + result_temp_min + "\ttemp_max: " + result_temp_min + "\n" +
            result_wind + "\n" +
            "clouds\tall: " + result_all + "\n" +
            "dt: " + result_dt + "\n" +
            "id: " + result_id + "\n" +
            "name: " + result_name + "\n" +
            "cod: " + result_cod + "\n" +
            "\n";
    }
}


search weather data from OpenWeatherMap
search weather data from OpenWeatherMap

Note:
- It's a simple example, without handle error condition; such as service unavailable, some item missing...etc.


OpenWeatherMap

The OpenWeatherMap service provides free weather data and forecast API suitable for any cartographic services like web and smartphones applications. Ideology is inspired by OpenStreetMap and Wikipedia that make information free and available for everybody. OpenWeatherMap provides wide range of weather data such as map with current weather, week forecast, precipitation, wind, clouds, data from weather Stations and many others. Weather data is received from global Meteorological broadcast services and more than 40 000 weather stations.

All weather data can be obtained in JSON, XML or HTML format.

http://openweathermap.org/

For example, you can search weather of London in JSON format with "http://api.openweathermap.org/data/2.5/weather?q=London,uk". The return result will be like this:

{"coord":{"lon":-0.12574,"lat":51.50853},"sys":{"country":"GB","sunrise":1374639224,"sunset":1374696019},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"gdps stations","main":{"temp":297,"humidity":61,"pressure":1011,"temp_min":295.37,"temp_max":298.71},"wind":{"speed":0.51,"gust":0.51,"deg":199},"clouds":{"all":76},"dt":1374693664,"id":2643743,"name":"London","cod":200}


Examples:
Parse JSON with Java SE and java-json, to search weather data from OpenWeatherMap.
Embed OpenWeatherMap in JavaFX WebView
Another example to embed Open Weather Map in JavaFX WebView


Add JAR in NetBeans

This post describe how to add third party Jar in NetBeans.

Download target JAR. For example, download java-json here, unzip it.

In NetBeans, right click your project, select Properties.


Select Category of Libraries, Compile tab, and click Add JAR/Folder button.


Browse to select the downloaded/unzipped jar file, click OK.


And click OK to finish.


Tuesday, July 23, 2013

Introduction to Java API for JSON Processing

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write.

The document Java API for JSON Processing: An Introduction to JSON introduce using the portable APIs to parse, generate, transform, and query JSON.

Setting up NetBeans IDE for Mobile Development on Windows

Setting up NetBeans IDE for Mobile Development on Windows

This screencast demonstrates the support for the Java ME SDK in NetBeans IDE, showing how to activate JavaME plugins and register the Java ME SDK in the IDE.

Monday, July 22, 2013

JavaFX example: apply Shadow effect

JavaFX example: apply Shadow effect
JavaFX example: apply Shadow effect
Further work on last example JavaFX: Move node to front, DropShadow effect will be added in Circles while moving. To remove the DropShadow effect, call setEffect(null) method of the node.



Example code:

package javafx_drawsomething;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_DrawSomething extends Application {
    
    Circle circle_Red, circle_Green, circle_Blue;
    double orgSceneX, orgSceneY;
    double orgTranslateX, orgTranslateY;
    
    DropShadow dropShadow;
    
    @Override
    public void start(Stage primaryStage) {
        
        //Create Circles
        circle_Red = new Circle(50.0f, Color.RED);
        circle_Red.setCursor(Cursor.HAND);
        circle_Red.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Red.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Green = new Circle(50.0f, Color.GREEN);
        circle_Green.setCursor(Cursor.MOVE);
        circle_Green.setCenterX(150);
        circle_Green.setCenterY(150);
        circle_Green.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Green.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Blue = new Circle(50.0f, Color.BLUE);
        circle_Blue.setCursor(Cursor.CROSSHAIR);
        circle_Blue.setTranslateX(300);
        circle_Blue.setTranslateY(100);
        circle_Blue.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Blue.setOnMouseDragged(circleOnMouseDraggedEventHandler);
                
        Group root = new Group();
        root.getChildren().addAll(circle_Red, circle_Green, circle_Blue);
        
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 400,350));
        
        primaryStage.setTitle("java-buddy");
        primaryStage.show();
        
        dropShadow = new DropShadow();
        dropShadow.setBlurType(BlurType.GAUSSIAN);
        dropShadow.setColor(Color.BLACK);
        dropShadow.setOffsetX(5.0);
        dropShadow.setOffsetY(5.0);
        dropShadow.setRadius(10.0);
        
        circle_Red.setOnMouseReleased(circleOnMouseReleasedEventHandler);
        circle_Green.setOnMouseReleased(circleOnMouseReleasedEventHandler);
        circle_Blue.setOnMouseReleased(circleOnMouseReleasedEventHandler);
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<MouseEvent> circleOnMousePressedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            orgSceneX = t.getSceneX();
            orgSceneY = t.getSceneY();
            orgTranslateX = ((Circle)(t.getSource())).getTranslateX();
            orgTranslateY = ((Circle)(t.getSource())).getTranslateY();
            
            ((Circle)(t.getSource())).toFront();
            ((Circle)(t.getSource())).setEffect(dropShadow);
        }
    };
    
    EventHandler<MouseEvent> circleOnMouseDraggedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            double offsetX = t.getSceneX() - orgSceneX;
            double offsetY = t.getSceneY() - orgSceneY;
            double newTranslateX = orgTranslateX + offsetX;
            double newTranslateY = orgTranslateY + offsetY;
            
            ((Circle)(t.getSource())).setTranslateX(newTranslateX);
            ((Circle)(t.getSource())).setTranslateY(newTranslateY);
        }
    };
    
    EventHandler<MouseEvent> circleOnMouseReleasedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            ((Circle)(t.getSource())).setEffect(null);
        }
    };
}


Sunday, July 21, 2013

Read online: Learning Java, Fourth Edition, by By Patrick Niemeyer and Daniel Leuck

Learning Java, Fourth Edition, by By Patrick Niemeyer and Daniel Leuck

Java is the preferred language for many of today’s leading-edge technologies—everything from smartphones and game consoles to robots, massive enterprise systems, and supercomputers. If you’re new to Java, the fourth edition of this bestselling guide provides an example-driven introduction to the latest language features and APIs in Java 6 and 7. Advanced Java developers will be able to take a deep dive into areas such as concurrency and JVM enhancements.

You’ll learn powerful new ways to manage resources and exceptions in your applications, and quickly get up to speed on Java’s new concurrency utilities, and APIs for web services and XML. You’ll also find an updated tutorial on how to get started with the Eclipse IDE, and a brand-new introduction to database access in Java.

Read online

Table of Contents

  • A Modern Language
  • A First Application
  • Tools of the Trade
  • The Java Language
  • Objects in Java
  • Relationships Among Classes
  • Working with Objects and Classes
  • Generics
  • Threads
  • Working with Text
  • Core Utilities
  • Input/Output Facilities
  • Network Programming
  • Programming for the Web
  • Web Applications and Web Services
  • Swing
  • Using Swing Components
  • More Swing Components
  • Layout Managers
  • Drawing with the 2D API
  • Working with Images and Other Media
  • JavaBeans
  • Applets
  • XML


Saturday, July 20, 2013

JavaFX: Move node to front

To move any node to front position, simple toFront() method of the object. The method toFront() moves this Node to the front of its sibling nodes in terms of z-order. This is accomplished by moving this Node to the last position in its parent's content ObservableList. This function has no effect if this Node is not part of a group.

reference: http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#toFront()

Modify the code in last example JavaFX: Drag and Move something, call ((Circle)(t.getSource())).toFront() in handle(MouseEvent t) of circleOnMousePressedEventHandler to move the clicked circle to front position.

Move circle to front position
Move circle to front position


package javafx_drawsomething;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_DrawSomething extends Application {
    
    Circle circle_Red, circle_Green, circle_Blue;
    double orgSceneX, orgSceneY;
    double orgTranslateX, orgTranslateY;
    
    @Override
    public void start(Stage primaryStage) {
        
        //Create Circles
        circle_Red = new Circle(50.0f, Color.RED);
        circle_Red.setCursor(Cursor.HAND);
        circle_Red.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Red.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Green = new Circle(50.0f, Color.GREEN);
        circle_Green.setCursor(Cursor.MOVE);
        circle_Green.setCenterX(150);
        circle_Green.setCenterY(150);
        circle_Green.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Green.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Blue = new Circle(50.0f, Color.BLUE);
        circle_Blue.setCursor(Cursor.CROSSHAIR);
        circle_Blue.setTranslateX(300);
        circle_Blue.setTranslateY(100);
        circle_Blue.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Blue.setOnMouseDragged(circleOnMouseDraggedEventHandler);
                
        Group root = new Group();
        root.getChildren().addAll(circle_Red, circle_Green, circle_Blue);
        
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 400,350));
        
        primaryStage.setTitle("java-buddy");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<MouseEvent> circleOnMousePressedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            orgSceneX = t.getSceneX();
            orgSceneY = t.getSceneY();
            orgTranslateX = ((Circle)(t.getSource())).getTranslateX();
            orgTranslateY = ((Circle)(t.getSource())).getTranslateY();
            
            ((Circle)(t.getSource())).toFront();
        }
    };
    
    EventHandler<MouseEvent> circleOnMouseDraggedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            double offsetX = t.getSceneX() - orgSceneX;
            double offsetY = t.getSceneY() - orgSceneY;
            double newTranslateX = orgTranslateX + offsetX;
            double newTranslateY = orgTranslateY + offsetY;
            
            ((Circle)(t.getSource())).setTranslateX(newTranslateX);
            ((Circle)(t.getSource())).setTranslateY(newTranslateY);
        }
    };
}


Next: Apply Shadow effect while moving the Circles

Tuesday, July 16, 2013

OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam


OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam

This book is a comprehensive guide to the 1Z0-803 exam. You'll explore a wide range of important Java topics as you systematically learn how to pass the certification exam. Each chapter starts with a list of the exam objectives covered in that chapter. You'll find sample questions and exercises designed to reinforce key concepts and to prepare you for what you'll see in the real exam, along with numerous tips, notes, and visual aids throughout the book.

About This Book

To earn the OCA Java SE 7 Programmer Certification, you need to know your Java inside and out, and to pass the exam it's good to understand the test itself. This book cracks open the questions, exercises, and expectations you'll face on the OCA exam so you'll be ready and confident on test day.
OCA Java SE 7 Programmer I Certification Guide is a comprehensive guide to the 1Z0-803 exam. You'll explore important Java topics as you systematically learn what is required. Each chapter starts with a list of exam objectives, followed by sample questions and exercises designed to reinforce key concepts. It provides multiple ways to digest important techniques and concepts, including analogies, diagrams, flowcharts, and lots of well-commented code.

Written for developers with a working knowledge of Java who want to earn the OCA Java SE 7 Programmer I Certification.

Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.

What's Inside
  • Covers all exam topics
  • Hands-on coding exercises
  • How to avoid built-in traps and pitfalls
About the Author


Mala Gupta has been training programmers to pass Java certification exams since 2006. She holds OCA Java SE7 Programmer I, SCWCD, and SCJP certifications.

Table of Contents
  1. Introduction
  2. Java basics
  3. Working with Java data types
  4. Methods and encapsulation
  5. String, StringBuilder, Arrays, and ArrayList
  6. Flow control
  7. Working with inheritance
  8. Exception handling
  9. Full mock exam

JavaFX: Drag and Move something

The example demonstrate how to implement EventHandler for OnMousePressed and OnMouseDragged evenets, to detect mouse drag and move something.

Drag and Move something
Drag and Move something


package javafx_drawsomething;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_DrawSomething extends Application {
    
    Circle circle_Red, circle_Green, circle_Blue;
    double orgSceneX, orgSceneY;
    double orgTranslateX, orgTranslateY;
    
    @Override
    public void start(Stage primaryStage) {
        
        //Create Circles
        circle_Red = new Circle(50.0f, Color.RED);
        circle_Red.setCursor(Cursor.HAND);
        circle_Red.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Red.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Green = new Circle(50.0f, Color.GREEN);
        circle_Green.setCursor(Cursor.MOVE);
        circle_Green.setCenterX(150);
        circle_Green.setCenterY(150);
        circle_Green.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Green.setOnMouseDragged(circleOnMouseDraggedEventHandler);
        
        circle_Blue = new Circle(50.0f, Color.BLUE);
        circle_Blue.setCursor(Cursor.CROSSHAIR);
        circle_Blue.setTranslateX(300);
        circle_Blue.setTranslateY(100);
        circle_Blue.setOnMousePressed(circleOnMousePressedEventHandler);
        circle_Blue.setOnMouseDragged(circleOnMouseDraggedEventHandler);
                
        Group root = new Group();
        root.getChildren().addAll(circle_Red, circle_Green, circle_Blue);
        
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 400,350));
        
        primaryStage.setTitle("java-buddy");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<MouseEvent> circleOnMousePressedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            orgSceneX = t.getSceneX();
            orgSceneY = t.getSceneY();
            orgTranslateX = ((Circle)(t.getSource())).getTranslateX();
            orgTranslateY = ((Circle)(t.getSource())).getTranslateY();
        }
    };
    
    EventHandler<MouseEvent> circleOnMouseDraggedEventHandler = 
        new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            double offsetX = t.getSceneX() - orgSceneX;
            double offsetY = t.getSceneY() - orgSceneY;
            double newTranslateX = orgTranslateX + offsetX;
            double newTranslateY = orgTranslateY + offsetY;
            
            ((Circle)(t.getSource())).setTranslateX(newTranslateX);
            ((Circle)(t.getSource())).setTranslateY(newTranslateY);
        }
    };
}




New Java EE 7 Tutorial available

The NEW Java EE 7 tutorial is now available along with the SDK/GlassFish 4. There's both a PDF version and an HTML version.


In addition, the team behind the tutorials has also developed a great sample/starter application for Java EE 7 named Your First Cup: An Introduction to the Java EE Platform that should be very helpful to beginners.



Source: https://blogs.oracle.com/theaquarium/entry/java_ee_7_tutorial_available

Monday, July 15, 2013

NetBeans IDE 7.4 Beta available now

NetBeans IDE 7.4 Beta extends the advanced HTML5 development support introduced in NetBeans IDE 7.3 to Java EE and PHP application development, while offering new support for hybrid HTML5 application development on the Android and iOS platforms. In addition, this release provides support for working with preview versions of JDK 8, and includes continued enhancements to JavaFX, C/C++ and more.

Source: NetBeans IDE 7.4 Beta Release Information


Drawing something on JavaFX

Example to draw something on JavaFX:

draw something on JavaFX
draw something on JavaFX


package javafx_drawsomething;

import javafx.application.Application;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_DrawSomething extends Application {
    
    Circle circle_Red, circle_Green, circle_Blue;
    
    @Override
    public void start(Stage primaryStage) {
        
        //Create Circles
        circle_Red = new Circle(50.0f, Color.RED);
        circle_Red.setCursor(Cursor.HAND);
        
        circle_Green = new Circle(50.0f, Color.GREEN);
        circle_Green.setCursor(Cursor.MOVE);
        circle_Green.setCenterX(150);
        circle_Green.setCenterY(150);
        
        circle_Blue = new Circle(50.0f, Color.BLUE);
        circle_Blue.setCursor(Cursor.CROSSHAIR);
        circle_Blue.setTranslateX(300);
        circle_Blue.setTranslateY(100);
                
        Group root = new Group();
        root.getChildren().addAll(circle_Red, circle_Green, circle_Blue);
        
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 400,350));
        
        primaryStage.setTitle("java-buddy");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Saturday, July 13, 2013

JavaFX example: Set cursor of nodes

The setCursor(Cursor value) method of javafx.scene.Node set the mouse cursor for this Node and subnodes. The javafx.scene.Cursor class encapsulate bitmaps of various mouse cursor you can use.

Example:



package javafx_cursor;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Cursor extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        btn.setCursor(Cursor.OPEN_HAND);
        root.setCursor(Cursor.CROSSHAIR);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Wednesday, July 10, 2013

Getting Started with Oracle Java ME Embedded and Raspberry Pi

Getting Started with Oracle Java ME Embedded and Raspberry Pi

Learn with Simon Ritter, Java Technology Evangelist, how Oracle Java ME Embedded and Raspberry Pi Model B can work together to create some interesting types of applications!

Tuesday, July 9, 2013

Educational content from Java Virtual Developer Day are online now

Watch educational content from Java Virtual Developer Day, covering Java SE, Java EE, and Java Embedded.

Visit https://oracle.6connex.com/portal/java2013/, register and enjoy the content.

Join this FREE virtual event where you will learn about:
  • HTML5 applications, improved developer productivity, and meeting enterprise demands using Java EE 7
  • What's new in Java that helps you begin programming on a wide range of embedded devicesWhat's new in Java that helps you begin programming on a wide range of embedded devices
  • Language improvements in Java SE to accelerate application development
Oracle Java 2013
Oracle Java 2013


Tuesday, July 2, 2013

Compare Strings in Java

Example of Comparing Strings in Java:

package javaex_cmpstring;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaEx_CmpString {
    
    String s1 = new String("java-buddy");
    String s2 = new String("java-buddy");
    String s3 = "java-buddy";
    String s4 = "java-buddy";
    String s5 = "java-" + "buddy";
    //s3, s4, and s5 will reference to the same object of "java-buddy"

    public static void main(String[] args) {
        new JavaEx_CmpString().CmpString();
    }
    
    private void CmpString(){
        System.out.println("s1==s2: " + String.valueOf(s1==s2));
        System.out.println("s3==s4: " + String.valueOf(s3==s4));
        System.out.println("s1==s3: " + String.valueOf(s1==s3));
        System.out.println("s3==s5: " + String.valueOf(s3==s5));
        
        System.out.println("s1.equals(s2): " + s1.equals(s2));
        System.out.println("s3.equals(s4): " + s3.equals(s4));
        System.out.println("s1.equals(s3): " + s1.equals(s3));
        System.out.println("s3.equals(s5): " + s3.equals(s5));
        
    }
}

Compare Strings in Java
Compare Strings in Java


Monday, July 1, 2013

Get offline API reference using "javac -Xprint"

http://docs.oracle.com/javase/7/docs/api/ provide API specification for the Java™ Platform, Standard Edition.

http://docs.oracle.com/javase/7/docs/api/
http://docs.oracle.com/javase/7/docs/api/
Alternatively, you can get API summary with the command "javac -Xprint".

example:
javac -Xprint java.nio.file.Paths


javac -Xprint java.nio.file.Paths
javac -Xprint java.nio.file.Paths