Use the compiled javafx script technology to create a rich Internet Application

Source: Internet
Author: User

By James L. Weaver,
2/29/08

 

The javafx series of technologies currently include the javafx script and javafx mobile platforms. The latter is a platform for mobile phones and other mobile devices. The 18 articles in this series focus on the javafx Script Programming Language,
This is a simple and elegant scripting language that fully utilizes the powerful functions of the Java platform. Further, these series of articles cover compiled javafx
Script, which goes through a complete development cycle. You may have learned that javafx script has an interpreted version, which serves as the prototype of the compiled version.
Javafx script is static and fully object-oriented.

You can see that using javafx script, you can easily develop a responsive rich graphic user interface (GUI ). A part of its charm is that even if developers do not have deep programming knowledge, they can develop graphical content to form an amazing user interface (UI ).

Java SE 6 Update n is the name of some updates in Java platform, Standard Edition 6 (Java SE 6), which is usually abbreviated as 6un and implements the latest JVM version.*And significantly accelerate the startup of Java applets and applications. In addition, the javafx script is compiled into a JVM bytecode, so we can provide a graphical rich client that can be quickly deployed and executed.

Now you have a basic understanding of javafx technology and the meaning of Java SE 6 Update N. Let's look at some compiled javafx
Script code, which is a little more complex than a typical Hello World Program. With this code, you can experience the creation of components including the UI and 2D
How simple is the compiled javafx program of graphics. The next section shows how to compile and run the sample program.

Directory

 

- Get javafx script compiler
- Compile and run the hellocompiledjavafx Program
- Understand the hellocompiledjavafx application code
- Define declarative code for the user interface
- Use frame class
- Create string characters
- Use layout Components
- Event Processing and message dialog box
- Draw on the canvas
- Define font
- Conclusion
- More information

 

Get javafx script compiler

Before compiling and running the javafx script program, you must first obtain the latest version of the javafx compiler. Follow these steps. Note: You must use JRE 5 or later to compile and run the javafx script program.

  1. Download the latest version of the compiler.
  2. Setarchive.zipDecompress the file to a directory in the system.
  3. SetPATHEnvironment variable to include and decompressarchive.zipDirectory used for filearchive/openjfx-compiler/dist/binSubdirectory.

Compile and run the hellocompiledjavafx Program

Because the program usespackageThe source code must be in the directory with the same directory name and package name. Save the programmypackageName in the directoryHelloCompiledJavaFX.fx. To compile this program, set the current directorymypackageDirectory and executejavafxcRun the following command:

javafxc HelloCompiledJavaFX.fx

 

To run the program, access the directory where the package is saved, and enter the following command:

javafx mypackage.HelloCompiledJavaFX

 

Figure 1 shows the window that will appear.

Figure 1: Main Window of the application

 

After the click me button is activated, the dialog box shown in 2 is displayed.

Figure 2: message dialog box

 

Code example 1 shows the source code of this simple javafx script program.

Sample Code 1
/*
* HelloCompiledJavaFX.fx - A "Hello World" style, but slightly more
* sophisticated, compiled JavaFX Script example
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a compiled JavaFX Script example.
*/
package mypackage;

import javafx.ui.*;
import javafx.ui.canvas.*;

Frame {
title: "Hello Rich Internet Applications!"
width: 550
height: 200
background: Color.WHITE
visible: true
content:
BorderPanel {
top:
FlowPanel {
content:
Button {
text: "Click Me"
action:
function():Void {
MessageDialog {
title: "JavaFX Script Rocks!"
// This string has a newline in the source code
message: "JavaFX Script is Simple, Elegant,
and Leverages the Power of Java"
visible: true
}
}
}
}
center:
Canvas {
content:
Text {
font:
Font {
faceName: "Sans Serif"
style: FontStyle.BOLD
size: 24
}
x: 20
y: 40
stroke: Color.BLUE
fill: Color.BLUE
content: "JavaFX Script Makes RIA Development Easy"
}
}
}
}

 

Let's carefully check the source code.

Understand the hellocompiledjavafx application code

Like the Java programming language, javafx technology includes two types of Annotations: multi-line and single-line annotations.

  • Multi-line commentIt starts with two/*And end with the same two characters, but in reverse order (*/). Any content between the start character and the end character will be ignored. The first part of code example 1 shows an example of multi-line comments.
  • Single line commentTake two//Start with the character. All content after the two characters will be ignored. Sample Code 1 shows an example of a single line comment in the near middle. For ease of viewing, the following example is shown again:

    // This string has a newline in the source code.

Same as Java,PackageDeclare folders similar to those in a file system. It provides a way to logically organize the source code file of an application. In this example, the package ismypackage, Which indicatesHelloCompiledJavaFX.fxThe source code is located inmypackage. The package name may consist of multiple nodes. For example,com.sun.fooThe package name indicates that the source code file is namedfooIn the folder namedsunAndsunThe folder is in the com folder. Note that the package name usually starts with the domain name of the company or organization that develops the application-in the reverse order, starting with a top-level domain name, for examplecomOrorg. Package declaration is optional. In addition to the most common applications, other programs should use package Declaration, which is a best practice. If the package declaration is used, the package declaration statement must be at the top of the source code and cannot contain spaces or comments.

Continue to use your Java programming language knowledge. You will see that the javafx script language also containsImportStatement. The javafx program usually uses a library composed of javafx code (and some java code. In this example, each import statement indicates the position or package of some javafx classes,HelloCompiledJavaFX.fxThe code for the rest of the file will depend on these classes to output parts and graphics to the screen. The Import Statement can end with an asterisk (*), indicating that the program may use any class in the package. An alternative method is to specify each class in use, as shown in the following example:

import javafx.ui.Frame;

 

Except for the most common applicationspackageDeclare the source code of the Organization. ForpackageThe source code file of the statement.importThe statement indicates the use of the classes contained in it.

Define declarative code for the user interface

Javafx
An exciting feature of technology is its ability to express graphical user interfaces (guis) with a simple, consistent, and powerful declarative syntax ). Declarative Programming is composed of a single expression, while procedural programming is composed of multiple
Continuous execution expressions. Javafx script supports both types of programming. However, using declarative syntax is a best practice whenever possible.

Most sample applications in code example 1 are declarative: composed of a single expression. A declarative expression first definesFrameObject, followed by an open curly braces, ending with a matching curly braces in the last line of the program. The nested content isFrameObject attributes, includingBorderPanelLayout componentcontentAttribute,BorderPanelIs implemented on the Java platform.BorderLayoutA gui component. The content attribute is nested.BorderPanelPartstopAndcenterAttribute, which is assigned with oneFlowPanelLayout parts andCanvasParts. This nesting will continue until it fully expresses the UI's inclusion structure.

Declarative code automatically creates an instance of each javafx class in the expression, also known as an object. It also allocates values to the attributes of the new instance. For example, to view the code for creating a font instance:

Font {
faceName: "Sans Serif"
style: FontStyle.BOLD
size: 24
}

 

These codes create javafxFontClass and set the valueSans SerifAssigned to newFontInstancefaceNameAttribute. It alsoFontStyle.BOLDThe constant (static attribute) value is assignedstyleAttribute, Set24AssignedsizeAttribute. Note that each attribute name is followed by a colon (:In the javafx declarative syntax, this indicates "assigning the expression value on the right to the attribute on the left ". These concepts are the same for other classes in this program:Frame,BorderPanel,FlowPanel,Button,MessageDialog,CanvasAndText. Let's look at these classes separately.

Use frame class

FrameA Gui window with its own boundaries and can contain other GUI components.

Like most classes,FrameClass has a set of attributes. As shown in code example 1,FrameThe property set of a part includes the following:

  • titleDisplay in the title bar of the window.
  • heightAndwidthThe attribute is measured in pixels to determine the initial size of the window.
  • backgroundAttribute specifiedFrameBackground color.
  • visibleProperty ControlFrameWhether the object is displayed on the screen.
  • contentAttribute DefinitionFrameObject content. In this example,FrameThe object will containBorderPanelLayout part, which contains other parts.

Create string characters

Javafx technology provides several data types, one of which isStringIt consists of zero or multiple strings. See the followingFrameObjecttitleProperties,StringDouble quotation marks are used to enclose a group of characters:

title: "Hello Rich Internet Applications!"

 

To embed a linefeed into a string, you only need to continue the string in the new line. The following code from the example shows this:

message: "JavaFX Script is Simple, Elegant,
and Leverages the Power of Java"

 

In addition, you can also choose to use single quotesStringCharacter.

Use layout Components

A notable feature of javafx script is that it can use simple declarative code to represent a GUI and its layout. This is because javafx
Script uses layout components (some UI components), instead of requiring you to create an instance of the layout manager and associate it with the UI component. The latter is exactly the Java
Technical practices. Figure 3 shows the layout policy used in this application.

Figure 3: determine the main window of the layout widget

 

By comparing the source code in figure 3 and sample code 1, you can see how easy it is to use javafx technology to define a complex cross-platform UI.BorderPanelBehavior of layout components andBorderLayoutThe Java UI container managed by the manager has the same behavior: the UI parts can be associatedtop,left,right,bottomAndcenterAttribute. The upper, lower, left, and right areas only occupy the space required to place their respective parts, while the center area occupies the remaining space. And JavaBorderLayoutSame manager, placed inBorderPanelThe parts in will be enlarged to the appropriate size of the placed area.

Similarly,FlowPanelAnd JavaFlowLayoutThe behavior of the Java UI container under management is the same: it allows the components to move from the left side to the right side, and can also be included inFlowPanel. And JavaFlowLayoutSame manager, placed inFlowPanelThe parts in will keep their default size, insteadBorderPanelThe widget is enlarged.

Event Processing and message dialog box

Let's look at the declarative code block under idea. It firstButtonClass:

Button {
text: "Click Me"
action:
function():Void {
MessageDialog {
title: "JavaFX Script Rocks!"
// This string has a newline in the source code
message: "JavaFX Script is Simple, Elegant,
and Leverages the Power of Java"
visible: true
}
}
}

 

When the user activates this button, the call is assignedactionIn this example, an anonymous function of the attribute is created.MessageDialogClass. BecausevisibleAttribute is true, newMessageDialogThe instance is displayed on the screen and has the corresponding title and message, as shown in Figure 4. For convenience, it repeats the screen in Figure 1:

Figure 3: determine the main window of the layout widget

 

Figure 4: message dialog box

 

Note: messages in the dialog box are displayed in two rows, which are determined by the way messages are distributed to attributes, as described in the create string character section.

Draw on the canvas

ViewCanvasPay attention to the related code.CanvasAssignedBorderPanel. As you can see earlier, declarative code is used to represent parts in the UI inclusion structure. Now we will use declarative code inCanvas. You will useTextClass inCanvasThis is a 2D graphics class provided by javafx script.xAndyThe display position in pixels in the upper left corner of the text.TextClasscontentProperty contains the string to be drawn, andfontAttribute specifies the appearance of the text to be drawn.

Canvas {
content:
Text {
font:
Font {
faceName: "Sans Serif"
style: FontStyle.BOLD
size: 24
}
x: 20
y: 40
stroke: Color.BLUE
fill: Color.BLUE
content: "JavaFX Script Makes RIA Development Easy"
}
}

 

Define font

Finally, in the previous code snippet, you can seeFontClass. This class is used to specifyTextThe Appearance Features of the object will be usedfaceName,styleAndsizeAttribute.

Conclusion

In this article, you have learned the following:

  • Javafx script can easily develop responsive cross-platform rich GUI, while Java SE 6 Update n can solve cross-platform problems and improve the deployment Speed.
  • Javafx script allows you to use simple declarative syntax to represent complex cross-platform guis. You can easily represent GUI parts, layout parts, and 2D images.
  • Javafx script is static and fully object-oriented.
  • Javafx script comments andpackageAndimportThe statement is exactly the same as the Java programming language.
  • The anonymous function assigned to the attribute is responsible for event processing, as shown in figureButtonClassactionProperties.
  • You can download and use the latest javafx script compiler to compile and run your javafx script program.

* In this website, the term "Java Virtual Machine" or "JVM" indicates a virtual machine on the Java platform.

More information
  • Javafx technology at a glance
  • Java SE 6 Update n early access
  • Java SE 6 Update n new plug-in
  • Java SE 6 Update n Java quick starter (jqs)
  • Download JRE 5 or later
  • Download the latest compiler version
  • James Weaver's blog will help you become javafxpert

About the author

James L. (Jim) WeaverIs the CTO of Lat, Inc. And is a Java champion. He is a writer and speaker and provides training and consulting services on Java and javafx technologies. His latest book is javafx Script: Dynamic Java scripting for rich Internet/client-side applications. He also often posts on a blog devoted to helping readers become "javafx experts.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.