JavaFX: Tutorials and Demos

7 September, 2008 at 10:07 3 comments

JavaFX imageJavaFX is a family of products for creating Rich Internet Applications (RIAs) with immersive media and content. The JavaFX products include a runtime and tools suite that web scripters, designers and developers can use to quickly build and deliver expressive rich interactive applications for desktop, mobile, TV and other platforms. Currently JavaFX consists of JavaFX Script and JavaFX Mobile.

In press previews for JavaFX, Sun Fellow James Gosling explained:

Most scripting languages are oriented at banging out Web pages. This is oriented around interfaces that are highly animated.

James Gosling,

There are parts of the world where a person’s desktop computer is their cell phone, and that’s the kind of end point that we’re going to get to,

James Gosling,

JavaFX is anticipated to compete on the desktop with Adobe Flash Player, Adobe AIR, OpenLaszlo, and Microsoft Silverlight. It may also target Blu-ray Disc’s interactive BD-J platform, although as yet no plans for a Blu-ray release have been announced.

Tutorials on javafx.com

Creating GUIs Using JavaFX Script

This lesson describes the JavaFX SDK Runtime functionality for creating GUIs. It gives you a high-level explanation of the feature and offers instructions on how to create GUIs using the functionality.

Feature Overview

The JavaFX SDK runtime is the foundation library of JavaFX platform, allowing content developers, designers, and GUI architects to quickly and easily create GUIs for Rich Internet Applications. Based on the underlying scene graph functionality, the library provides the ability to present objects in scenes such as a frame containing a circle with a defined filling and stroke, and apply different types of lighting, animation, and transformation effects. For more information about the scene graph API, see the project page at scenegraph.dev.java.net and Presenting Visual Objects lesson.

Practical Examples – Creating Simple Graphics

To learn how to create the GUI using JavaFX Script, consider a task of creating simple graphics: a rounded rectangle and a text string with a drop shadow.

The following code sample shows how you do it in a traditional way using Java 2D:

import java.applet.Applet;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.*;
...
public class SimpleButton extends Applet {
...
	public void paint(Graphics g) {
	  Graphics2D g2 = (Graphics2D) g;
	  g.setColor(Color.LIGHT_GRAY);
	  g2.fillRoundRect(10, 10, 200, 50, 15, 15);

	  Font font = new Font("Serif", Font.BOLD, 20);
	  g.setFont(font);
	  String textString = "Java 2D";
	  FontRenderContext frc = ((Graphics2D)g).getFontRenderContext();
	  Rectangle2D bounds = font.getStringBounds(textString, frc);
	  int wText = (int)bounds.getWidth();
	  int TextX = 10 + 200/2 - wText/2;

	  g.setColor(Color.DARK_GRAY);
	  g.drawString(textString, TextX + 1, 39);
	  g.setColor(Color.YELLOW);
	  g.drawString(textString, TextX, 40);
	}
...
}
Java2D Sample

Figure 1: Java 2D Sample

To drop a shadow, this code sets a contrast color and uses an additional drawString method with offset coordinates.

The JavaFX Script Language and JavaFX Runtime classes enable developers to render the same graphic context more easily and more clearly:

import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.geometry.*;
import javafx.scene.text.*;
import javafx.scene.effect.*;
import javafx.ext.swing.*;

SwingFrame {
  title: "Simple (JavaFX demo)"
  width: 228
  height: 98
  content: Canvas {
    content: Group {
      content: [
        Rectangle {
          x: 10   y: 10
          width: 200   height: 50
          arcWidth: 15   arcHeight: 15
          fill: Color.web("#C0C0C0")
        },
        Text {
          x: 110   y: 40
          content: "JavaFX"
          font: Font {
            name: "Serif"
            size: 20
            style: FontStyle.BOLD
          }
          fill: Color.YELLOW
          horizontalAlignment: HorizontalAlignment.CENTER
          effect: DropShadow {
            offsetX: 2   offsetY: -2   radius: 6
            color: Color.BLACK
          }
        }
      ]
    }
  }
  visible: true
}

This code sample defines a Group object containing two elements: Rectangle and Text. Shape parameters and coordinates as well as font and colors are set using corresponding attributes – x , y, font, size, style, fill and color. The effect attribute applies a drop shadow to the Text element.

To enhance this code, apply a lighting effect to the Group:

import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.geometry.*;
import javafx.scene.text.*;
import javafx.scene.effect.*;
import javafx.scene.effect.light.*;
import javafx.ext.swing.*;

Group {
  content: [
    Rectangle{...}
    Text {...}
  ] effect: Lighting{light: DistantLight {azimuth: 225}}
}
JavaFX Sample

Figure 2: JavaFX Script Sample

The azimuth attribute defines a direction angle for the light source on the XY plane, in degrees.
More visual effects are available in the javafx.scene.effect and javafx.scene.effect.light packages. Refer to the API doc or to API Reference for more information. The entire code of this program is available in the JavaFXGraphics.fx file.

Applying Data Binding

Data binding is one of the advantageous features in JavaFX Script Language. It enables all public attributes and functions to be bound. For example, you can bind the window title to the TextField, so whatever you type automatically appears in the window title without handling event listeners. For the graphical sample, you create a slider to vary the angle of the distant light source.

Data Binding Sample

Figure 3: Data Binding Sample

To add the slider to the Group, use the ComponentView class.

var slider = Slider{minimum: 0 maximum: 360 value: 20};

(more)

Demo

The demo application is a stopwatch widget that measures and displays time intervals accurate to within hundredths of a second. The application interface is a dial that has a second hand, two small dials that display tenths and hundredths of a second, and a digital display that shows time elapsed in minutes, seconds, and tenths and hundredths of a second. On the top of the main dial there are two buttons, green and red. The green button starts or stops the time measure. Once the green button is pressed during time measure, the stopwatch stops indicating the time elapsed, however the actual time measuring continues. This feature allows recording intermediate results. The red button resets the elapsed time.

 Stopwatch Widget

Figure 1: Stopwatch Widget

Creating the Application GUI

The demo uses a number of JavaFX SDK Runtime classes to build the application UI and implement graphical effects.

The following code draws the inner and the outer circle of the main stopwatch. Note the use of the Circle, LinearGradient, and RadialGradient classes. These classes are used to draw circles with a 140- and 134- pixel radius and fill them with the linear and radial gradient respectively. The radius of the circle is defined by the radius attribute, the start and end colors of the gradient are defined using the Stop and color attributes.

Group { translateX: 40 translateY: 40 content: [
  Circle {
    centerX: 140
    centerY: 140
    radius: 140
    fill:LinearGradient { startX:0 startY:0 endX:1 endY:1
      stops: [
        Stop { offset:0 color: webcolor("#3c3c3c") },
        Stop { offset:1 color: webcolor("#010101") }
      ]
    }
  },
Circle {
  centerX: 140
  centerY: 140
  radius: 134
  fill: RadialGradient { centerX:0.5 centerY:0.5 radius:0.5
    stops: [
      Stop { offset:0 color: rgba(20,20,20,1) },
      Stop { offset:0.9499 color: rgba(20,20,20,1) },
      Stop { offset:0.95 color: rgba(20,20,20,1) },
      Stop { offset:0.975 color: rgba(20,20,20,1) },
      Stop { offset:1 color: rgba(84,84,84,0) }
    ]
  }
},
...

Also note that the Group class groups the two circles to enable them share a coordinate space and to be transformed as a group.

The numbers “0”, “15, “30”, “45” below the tick marks are implemented using the Text class. Here is the code that draws a white “0”.

Text {
  font: Font{name: "Courier" size: 16, style: FontStyle.BOLD}
  x: 141 y: 47
  content: "0"
  horizontalAlignment: HorizontalAlignment.CENTER
  fill: webcolor("#FFFFFF")
},
...

Note that the code uses font to set the font style and its size, x and y attributes to define the position of the tick mark, and content to display “0”. It also fills the tick mark with yellow using fill with a defined web code for this color.

The hand of the main dial comprises of two rectangles and a circle created using the Circle and Rectangle classes. Additionally, lighting effect is applied to the dial using Lighting class:

Group {
  content: [
    Group {
      content: [
        Circle {centerX: 140 centerY: 140 radius: 8
          fill: webcolor("#FF0000")},
        Rectangle{x: -1.5 y: -20 width: 3 height: 120
            fill: webcolor("#FF0000")
            rotate: bind handAngle
            translateX: 140
            translateY: 140},
        Rectangle{x: -1.5 y: -40 width: 3 height: 20
            fill: webcolor("#FFFFFF")
            rotate: bind handAngle
            translateX: 140
            translateY: 140}
      ]
      effect: Lighting{
        light: DistantLight {azimuth: 225}
      }
    }
  ]
...

(more)

Demo: JavaFX, creating a sphere with shadow on silveiraneto.net

Silveira Neto describes on your blog an interesting JavaFX demo and its graphics potentialities.

This is a short tutorial about some JavaFX elements like ellipses, circles, effects and gradients.

In the first code we are creating a frame with a ellipse with center in (120,140), 60 pixels of horizontal radius, 20 pixels of vertical radius and color black. We have also a circle with center in (100,100), 50 pixels of radius and color red. The idea is make this circle appears like a sphere and make the ellipse look like a shadow.


  1. import javafx.application.*;
  2. import javafx.scene.paint.*;
  3. import javafx.scene.geometry.*;
  4. Frame {
  5. title: "JavaFX Sphere", width: 300, height: 300, visible: true
  6. stage: Stage {
  7. content: [
  8. Ellipse {
  9. centerX: 120, centerY: 140, radiusX: 60, radiusY: 20
  10. fill: Color.BLACK
  11. },
  12. Circle { centerX: 100, centerY: 100, radius: 50, fill: Color.RED }
  13. ]
  14. }
  15. }

  1. import javafx.application.*;
  2. import javafx.scene.paint.*;
  3. import javafx.scene.geometry.*;
  4. Frame {
  5. title: "JavaFX Sphere", width: 300, height: 300, visible: true
  6. stage: Stage {
  7. content: [
  8. Ellipse {
  9. centerX: 120, centerY: 140, radiusX: 60, radiusY: 20
  10. fill: Color.BLACK
  11. },
  12. Circle { centerX: 100, centerY: 100, radius: 50, fill: Color.RED }
  13. ]
  14. }
  15. }

Now we will just add two thing, a effect and a radial gradient.

First we’ll just add javafx.scene.effect.* to our import list and just call the gaussian blur effect in our ellipse with

  1. effect: GaussianBlur{ radius: 20 } 
  1. effect: GaussianBlur{ radius: 20 }
    
    

Another Demo from silveiraneto.net: JavaFX, game demo

From James Weaver’s Blog I found another intersting JavaFx demo made by Silveira Neto.

I’ve featured Silveira Neto’s JavaFX work (play?) in a couple of recent posts, and it appears that he’s had gaming on his mind lately. Silveira is a CS student, CEJUG member and Sun Campus Ambassador at Federal University of Ceará.

Netoblackdotgame

His latest creation, shown above, is a game in which the player tries to vacuum up the dirty clouds with a sphere-shaped cleaner. It demonstrates several techniques in JavaFX, such as creating a side-scrolling game, capturing keyboard input, and ascertaining when a graphical object intersects with a pixel in another graphical object. You can see more information, including the source code and a YouTube video of the game being played, from Silveira’s blog post.

In a prior post, Silveira discusses how to create a side-scrolling game in JavaFX, showing the classes that he’s building to support it.

[wikipedia.org]
[http://javafx.com/]
[http://silveiraneto.net/]
[http://learnjavafx.typepad.com]
[javapassion.com]

Bookmark and Share

Advertisements

Entry filed under: Java, JavaFX. Tags: , .

The Internet’s Biggest Security Hole: exploiting the internet routing protocol BGP (Border Gateway Protocol) Mashup (hybrid web application): new generation of Web-based applications

3 Comments Add your own

  • 1. Ecko  |  14 June, 2010 at 08:22

    Thanks for sharing,,,

    Reply
  • […] searches are examples/tutorials explaining how things done in AWT can be done in JavaFX (see Example Article), which doesn’t answer my question, but does lead me to conjecture that there is no […]

    Reply
  • 3. roadster  |  16 January, 2014 at 13:37

    I really like what you guys tend to be up too. Such clever work and reporting!
    Keep up the wonderful works guys I’ve added you guys to my blogroll.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


IT Passion’s Store

Archives

Communities

Get the Source
OSGi supporter
JUG Milano

Upcoming Events



....

Blog Stats

  • 348,048 hits

My PageRank

What's My Google PageRank?

%d bloggers like this: