Javafx 简明教程
JavaFX - Overview
Rich Internet Applications 是那些提供类似桌面应用程序功能和体验的网络应用程序。与普通网络应用程序相比,它们为用户提供更好的视觉体验。这些应用程序作为浏览器插件或虚拟机提供,用于将传统的静态应用程序转换为增强、流畅、动画化且引人入胜的应用程序。
Rich Internet Applications are those web applications which provide similar features and experience as that of desktop applications. They offer a better visual experience when compared to the normal web applications to the users. These applications are delivered as browser plug-ins or as a virtual machine and are used to transform traditional static applications into more enhanced, fluid, animated and engaging applications.
不同于传统的桌面应用程序,RIA 无需任何附加软件即可运行。作为替代,您应该根据应用程序安装 ActiveX、Java、Flash 等软件。
Unlike traditional desktop applications, RIA’s don’t require to have any additional software to run. As an alternative, you should install software such as ActiveX, Java, Flash, depending on the Application.
在 RIA 中,图形呈现由客户端处理,因为它有一个插件,为丰富的图形提供支持。简而言之,RIA 中的数据处理在服务器端执行,而相关的对象处理在客户端执行。
In an RIA, the graphical presentation is handled on the client side, as it has a plugin that provides support for rich graphics. In a nutshell, data manipulation in an RIA is carried out on the server side, while related object manipulation is carried out on the client side.
我们有三种主要技术可以用来开发 RIA。这些技术包括以下内容: −
We have three main technologies using which we can develop an RIA. These include the following −
-
Adobe Flash
-
Microsoft Silverlight
-
JavaFX
Adobe Flash
该软件平台由 Adobe Systems 开发,用于创建 Rich Internet Applications。此外,您还可以构建其他应用程序,例如 Vector、动画、浏览器游戏、桌面应用程序、移动应用程序和游戏等。
This software platform is developed by Adobe Systems and is used in creating Rich Internet Applications. Along with these, you can also build other Applications such as Vector, Animation, Browser Games, Desktop Applications, Mobile Applications and Games, etc.
这是用于开发和执行 RIA 的最常用平台,桌面浏览器普及率为 96%。
This is the most commonly used platform for developing and executing RIA’s with a desktop browser penetration rate of 96%.
Microsoft Silverlight
与 Adobe Flash 一样,Microsoft Silverlight 也是一种用于开发和执行 Rich Internet Applications 的软件应用程序框架。最初,此框架用于流媒体。当前版本也支持多媒体、图形和动画。
Just like Adobe flash, Microsoft Silverlight is also a software application framework for developing as well as executing Rich Internet Applications. Initially this framework was used for streaming media. The present versions support multimedia, graphics, and animation as well.
该平台应用较少,桌面浏览器渗透率为 66%。
This platform is rarely used with a desktop browser penetration rate of 66%.
JavaFX
JavaFX 是一个 Java 库,您可以使用它来开发 Rich Internet Applications。通过使用 Java 技术,这些应用程序的浏览器普及率为 76%。
JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%.
What is JavaFX?
JavaFX 是一个用于构建 Rich Internet Applications 的 Java 库。使用此库编写的应用程序可以在多个平台上始终如一地运行。使用 JavaFX 开发的应用程序可以在各种设备上运行,例如台式机、移动电话、电视、平板电脑等。
JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library can run consistently across multiple platforms. The applications developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
要使用 Java 编程语言开发 GUI Applications ,程序员依赖于诸如 Advanced Windowing Toolkit 和 Swing 的库。在 JavaFX 出现后,这些 Java 程序员现在可以用丰富的内容高效地开发 GUI 应用程序。
To develop GUI Applications using Java programming language, the programmers rely on libraries such as Advanced Windowing Toolkit and Swing. After the advent of JavaFX, these Java programmers can now develop GUI applications effectively with rich content.
Need for JavaFX
要开发具有丰富功能的 Client Side Applications ,程序员过去依赖多种库来添加诸如媒体、用户界面控件、网络、2D 和 3D 等功能。JavaFX 在一个库中包含所有这些功能。除此之外,开发人员还可以访问 Java 库的现有功能,例如 Swing 。
To develop Client Side Applications with rich features, the programmers used to depend on various libraries to add features such as Media, UI controls, Web, 2D and 3D, etc. JavaFX includes all these features in a single library. In addition to these, the developers can also access the existing features of a Java library such as Swing.
JavaFX 提供了一组丰富的图形和媒体 API,并且通过硬件加速图形提高了现代 Graphical Processing Unit 的效率。JavaFX 还提供了可供开发人员组合图形动画和用户界面控件的界面。
JavaFX provides a rich set of graphics and media API’s and it leverages the modern Graphical Processing Unit through hardware accelerated graphics. JavaFX also provides interfaces using which developers can combine graphics animation and UI control.
人们可以使用基于 JVM 的技术(例如 Java、Groovy 和 JRuby)使用 JavaFX。如果开发人员选择 JavaFX,则无需学习其他技术,因为掌握上述任何技术都足以使用 JavaFX 开发 RIA。
One can use JavaFX with JVM based technologies such as Java, Groovy and JRuby. If developers opt for JavaFX, there is no need to learn additional technologies, as prior knowledge of any of the above-mentioned technologies will be good enough to develop RIA’s using JavaFX.
Features of JavaFX
以下是 JavaFX 的一些重要功能:
Following are some of the important features of JavaFX −
-
Written in Java − The JavaFX library is written in Java and is available for the languages that can be executed on a JVM, which include − Java, Groovy and JRuby. These JavaFX applications are also platform independent.
-
FXML − JavaFX features a language known as FXML, which is a HTML like declarative markup language. The sole purpose of this language is to define a user Interface.
-
Scene Builder − JavaFX provides an application named Scene Builder. On integrating this application in IDE’s such as Eclipse and NetBeans, the users can access a drag and drop design interface, which is used to develop FXML applications (just like Swing Drag & Drop and DreamWeaver Applications).
-
Swing Interoperability − In a JavaFX application, you can embed Swing content using the Swing Node class. Similarly, you can update the existing Swing applications with JavaFX features like embedded web content and rich graphics media.
-
Built-in UI controls − JavaFX library caters UI controls using which we can develop a full-featured application.
-
CSS like Styling − JavaFX provides a CSS like styling. By using this, you can improve the design of your application with a simple knowledge of CSS.
-
Canvas and Printing API − JavaFX provides Canvas, an immediate mode style of rendering API. Within the package javafx.scene.canvas it holds a set of classes for canvas, using which we can draw directly within an area of the JavaFX scene. JavaFX also provides classes for Printing purposes in the package javafx.print.
-
Rich set of API’s − JavaFX library provides a rich set of API’s to develop GUI applications, 2D and 3D graphics, etc. This set of API’s also includes capabilities of Java platform. Therefore, using this API, you can access the features of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions. The traditional Java Collections library was enhanced and concepts like observable lists and maps were included in it. Using these, the users can observe the changes in the data models.
-
Integrated Graphics library − JavaFX provides classes for 2d and 3d graphics.
-
Graphics pipeline − JavaFX supports graphics based on the Hardware-accelerated graphics pipeline known as Prism. When used with a supported Graphic Card or GPU it offers smooth graphics. In case the system does not support graphic card then prism defaults to the software rendering stack.
History of JavaFX
JavaFX 最初是由 Chris Oliver 开发的,他当时在 See Beyond Technology Corporation 公司工作。后来,该家公司在 2005 年被 Sun Microsystems 收购。
JavaFX was originally developed by Chris Oliver, when he was working for a company named See Beyond Technology Corporation, which was later acquired by Sun Microsystems in the year 2005.
以下是有关此项目的更多信息:
The following points give us more information of this project −
-
Initially this project was named as F3 (Form Follows Functions) and it was developed with an intention to provide richer interfaces for developing GUI Applications.
-
Sun Microsystems acquired the See Beyond company in June 2005, it adapted the F3 project as JavaFX.
-
In the year 2007, JavaFX was announced officially at Java One, a world wide web conference which is held yearly.
-
In the year 2008, Net Beans integrated with JavaFX was available. In the same year, the Java Standard Development Kit for JavaFX 1.0 was released.
-
In the year 2009, Oracle Corporation acquired Sun Microsystems and in the same year the next version of JavaFX (1.2) was released as well.
-
In the year 2010, JavaFX 1.3 came out and in the year 2011 JavaFX 2.0 was released.
-
The latest version, JavaFX8, was released as an integral part of Java on 18th of March 2014.
JavaFX - Environment
从 Java8 开始,JDK (Java Development Kit) 中包含 JavaFX 库。因此,要运行 JavaFX 应用程序,您只需要在您的系统中安装 Java8 或更高版本。
From Java8 onwards, the JDK (Java Development Kit) includes JavaFX library in it. Therefore, to run JavaFX applications, you simply need to install Java8 or later version in your system.
除此之外,像 Eclipse 和 NetBeans 这样的 IDE 为 JavaFX 提供支持。本小节将向您介绍如何以多种方式设置运行 JavaFX 应用程序的环境。
In addition to it, IDE’s like Eclipse and NetBeans provide support for JavaFX. This chapter teaches you how to set the environment to run JavaFX Applications in various ways.
Installing Java8
首先,您需要通过打开命令提示符并在其中键入 “java” 命令来验证您的系统中是否安装了 Java。
First of all, you will have to verify whether there is Java Installed in your system or not by opening the command prompt and typing the command “Java” in it.
如果您尚未在您的系统中安装 Java,命令提示符将显示以下屏幕截图中所示的消息。
If you haven’t installed Java in your system, the command prompt displays the message shown in the following screenshot.
然后按照以下步骤安装 Java。
Then install Java by following the steps given below.
Step 1 − 访问 JavaSE Downloads 页面,单击 JDK Download 按钮,如以下屏幕截图中突出显示
Step 1 − Visit the JavaSE Downloads Page, click on the JDK Download button as highlighted in the following screenshot
Step 2 − 单击下载按钮后,您将被重定向到 Java SE Development Kit 8 Downloads 页面。此页面为您提供适用于各个平台的 JDK 链接。
Step 2 − On clicking the Download button, you will be redirected to the Java SE Development Kit 8 Downloads page. This page provides you links of JDK for various platforms.
接受许可协议并单击相应链接下载所需软件。
Accept the license agreement and download the required software by clicking on its respective link.
例如,如果您正在使用 Windows 64 位操作系统,那么您需要下载以下屏幕截图中突出显示的 JDK 版本。
For example, if you are working on a windows 64-bit Operating System then you need to download the JDK version highlighted in the following screenshot.
单击突出显示的链接后,适用于 Windows 64 位操作系统的 Java8 开发工具包将下载到您的系统中。
On clicking the highlighted link, the Java8 Development Kit suitable for Windows 64-bit Operating System will be downloaded onto your system.
Step 3 − 运行下载的二进制可执行文件以开始安装 JDK8。
Step 3 − Run the downloaded binary executable file to start the installation of JDK8.
Step 4 − 选择安装目录。
Step 4 − Choose the Installation Directory.
Step 5 − 选择目标文件夹并单击下一步后,JavaFX 安装过程将开始显示进度条,如下面的屏幕截图所示。
Step 5 − On selecting the destination folder and clicking Next, the JavaFX installation process starts displaying the progress bar as shown in the following screenshot.
Step 6 − 根据需要更改安装目录,否则保留默认目录并继续进行。
Step 6 − Change the installation directory if needed, else keep the default ones and proceed further.
Step 7 − 单击关闭按钮完成安装过程,如下面的屏幕截图所示。
Step 7 − Finish the installation process by clicking the Close button as shown in the following screenshot.
Setting up the Path for Windows
安装 Java 后,您需要设置路径变量。假设您已将 Java 安装在 C:\Program Files\java\jdk1.8.0_91 目录中。
After installing Java, you need to set the path variables. Assume that you have installed Java in *C:\Program Files\java\jdk1.8.0_91*directory.
现在你可以执行以下步骤:
Now you can follow the steps that are given below −
-
Right-click on 'My Computer' and select 'Properties'.
-
Click on the 'Environment Variables' button under the 'Advanced' tab.
-
Now, alter the 'Path' variable so that it also contains the path to the Java executable. For Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32; C:\Program Files\java\ jdk1.8.0_91\bin'.
Setting NetBeans Environment of JavaFX
NetBeans8 为 JavaFX 提供内置支持。安装后,您可以在没有任何额外插件或 JAR 文件的情况下创建 JavaFX 应用程序。要设置 NetBeans 环境,您需要按照以下步骤操作。
NetBeans8 provides inbuilt support for JavaFX. On installing this, you can create a JavaFX application without any additional plugins or JAR files. To set up the NetBeans environment, you will need to follow the steps that are given below.
Step 1 − 访问 NetBeans website NetBeans 网站,然后单击下载按钮以下载 NetBeans 软件。
Step 1 − Visit the NetBeans website NetBeans website and click the Download button in order to download the NetBeans software.
Step 2 − 单击 Download 后,您将进入 NetBeans 软件的下载页面,该页面为各种 Java 应用程序提供 NetBeans 捆绑包。下载适用于 JavaSE 的 NetBeans 软件,如下面的屏幕截图所示。
Step 2 − On clicking Download, you will get to the Downloads page of the NetBeans software, which provides NetBeans bundles for various Java applications. Download the NetBeans software for JavaSE as shown in the following screenshot.
Step 3 − 单击此按钮后,名为 *netbeans-8.0-windows.exe * 的文件将下载到您的系统中。运行此文件以进行安装。运行此文件后,NetBeans 安装程序将启动,如下面的屏幕截图所示。
Step 3 − On clicking this button, a file named *netbeans-8.0-windows.exe * will be downloaded onto your system. Run this file in order to install it. On running this file, a NetBeans installer will start as shown in the following screenshot.
配置完成后,您将看到 Welcome Page of the installer 。
After completion of the configuration, you will see the Welcome Page of the installer.
Step 4 − 单击下一步按钮并继续安装。
Step 4 − Click the Next button and proceed with the installation.
Step 5 − 下一个窗口包含 NETBEANS IDE 8.0 license agreement 。仔细阅读并通过选中“我接受许可协议中的条款”旁边的复选框接受协议,然后单击 Next 按钮。
Step 5 − The next window holds the NETBEANS IDE 8.0 license agreement. Read it carefully and accept the agreement by checking the checkbox at “I accept the terms in the license agreement” and then click the Next button.
Step 6 − 在下一个窗口中,您将遇到 Junit 的许可协议,通过选中“我接受许可协议中的条款,安装 JUnit”旁边的单选按钮接受许可协议,然后单击 Next 。
Step 6 − In the next window, you will encounter the license agreement for Junit, accept it by selecting the radio button at “I accept the terms in the license agreement, Install JUnit” and click on Next.
Step 7 − 选择您需要安装 Netbeans 8.0 的目标目录。此外,您还可以浏览 Java Development Kit 在系统中安装的位置并单击 Next 按钮。
Step 7 − Choose the destination directory where you need the Netbeans 8.0 to be installed. Furthermore, you can also browse through the directory where Java Development Kit is installed in your system and click on the Next button.
Step 8 − 同样,为 Glassfish Server 安装选择目标目录。浏览 Java 开发工具包目录(现在是 Glassfish 参考),然后单击 Next 。
Step 8 − Similarly, choose the destination directory for Glassfish Server installation. Browse through the Java Development Kit directory (now for Glassfish Reference) and then click Next.
Step 9 − 勾选 Check for Updates 框以进行自动更新,然后单击安装按钮开始安装。
Step 9 − Check the Check for Updates box for automatic updates and click the Install button to start the installation.
Step 10 − 此步骤将启动 NetBeans IDE 8.0 安装,可能需要一段时间。
Step 10 − This step starts the installation of NetBeans IDE 8.0 and it may take a while.
Step 11 − 一旦进程完成,单击 Finish 按钮以完成安装。
Step 11 − Once the process is complete, click the Finish button to finish the installation.
Step 12 − 一旦您启动 NetBeans IDE,您将看到开始页面,如以下屏幕截图所示。
Step 12 − Once you launch the NetBeans IDE, you will see the start page as shown in the following screenshot.
Step 13 − 在文件菜单中,选择 New Project … 以打开新建项目向导,如以下屏幕截图所示。
Step 13 − In the file menu, select New Project… to open the New project wizard as shown in the following screenshot.
Step 14 − 在 New Project 向导中,选择 JavaFX 并单击 Next 。它开始为您创建一个新的 JavaFX 应用程序。
Step 14 − In the New Project wizard, select JavaFX and click on Next. It starts creating a new JavaFX Application for you.
Step 15 − 在 NewJavaFX Application 窗口中选择项目名称和项目位置,然后单击 Finish 。它使用给定的名称创建一个示例应用程序。
Step 15 − Select the name of the project and location of the project in the NewJavaFX Application window and then click Finish. It creates a sample application with the given name.
在本例中,创建了一个名为 javafxsample 的应用程序。在此应用程序中,NetBeans IDE 将生成一个名为 Javafxsample.java 的 Java 程序。如以下屏幕截图所示,该程序将在 NetBeans 源包 → javafxsample 中创建。
In this instance, an application with a name javafxsample is created. Within this application, the NetBeans IDE will generate a Java program with the name Javafxsample.java. As shown in the following screenshot, this program will be created inside NetBeans Source Packages → javafxsample.
Step 16 − 右键单击文件并选择 Run File 以运行此代码,如以下屏幕截图所示。
Step 16 − Right-click on the file and select Run File to run this code as shown in the following screenshot.
此自动创建的程序包含生成简单 JavaFX 窗口的代码,该窗口中有一个带有标签 Say ‘Hello World’ 的按钮。每次单击此按钮时,字符串 Hello World 都将显示在控制台上,如下所示。
This automatically created program contains the code which generates a simple JavaFX window having a button with the label Say ‘Hello World’ in it. Every time you click on this button, the string Hello World will be displayed on the console as shown below.
Installing JavaFX in Eclipse
JavaFX 中还提供了一个名为 *e(fx)*clipse 的插件。您可以使用以下步骤在 Eclipse 中设置 JavaFX。首先,确保您的系统中有 Eclipse。如果没有,请下载 Eclipse 并将其安装在系统中。
A plugin named *e(fx)*clipse is also available in JavaFX. You can use the following steps to set JavaFX in Eclipse. First of all, make sure that you have Eclipse in your system. If not, download and install Eclipse in your system.
一旦安装了 Eclipse,请按照下面给出的步骤在您的系统中安装 e(fx)clipse 。
Once Eclipse is installed, follow the steps given below to install e(fx)clipse in your system.
Step 1 − 在 Help 菜单中打开 Eclipse 并选择 Install New Software … 选项,如下所示。
Step 1 − Open Eclipse in the Help menu and select Install New Software… option as shown below.
单击后,它将显示 Available Software 窗口,如以下屏幕截图所示。
Upon clicking, it will display the Available Software window, as shown in the following screenshot.
在此窗口的文本框 Work with 中,您需要提供所需软件插件的链接。
In the text box Work with of this window, you need to provide the link of the plugin for the required software.
Step 2 − 单击 Add … 按钮。将插件名称指定为 e(fx)clipse 。接下来,将以下链接作为位置提供。 http://download.eclipse.org/efxclipse/updates-released/2.3.0/site/
Step 2 − Click the Add… button. Provide the name of the plugin as e(fx)clipse. Next, Provide the following link as a location. http://download.eclipse.org/efxclipse/updates-released/2.3.0/site/
Step 3 − 在指定插件的名称和位置后,单击确定按钮,如以下屏幕截图中所突出显示。
Step 3 − After specifying the name and location of the plugin, click the OK button, as highlighted in the following screenshot.
Step 4 − 添加插件后不久,您将找到两个用于 e(fx)clipse – install 和 e(fx)clipse – single components 的复选框。选中这两个复选框并单击 Add … 按钮,如以下屏幕截图所示。
Step 4 − Soon after you add the plugin, you will find two checkboxes for e(fx)clipse – install and e(fx)clipse – single components. Check both these checkboxes and click the Add… button as shown in the following screenshot.
Step 5 − 接下来,打开 Eclipse IDE。单击“文件”菜单,然后选择项目,如下面的屏幕截图所示。
Step 5 − Next, open your Eclipse IDE. Click the File menu and select Project as shown in the following screenshot.
Step 6 − 然后,你将得到一个窗口,在其中可以看到 Eclipse 提供的一个向导列表以创建项目。展开 JavaFX 向导,选择 JavaFX Project 并且单击 Next 按钮,如下面的屏幕截图所示。
Step 6 − Then, you will get a window where you can see a list of wizards provided by Eclipse to create a project. Expand the JavaFX wizard, select JavaFX Project and click the Next button as shown in the following screenshot.
Step 7 − 单击 Next 时,将在屏幕上打开“新建项目向导”。在这里,你可以键入所需的项目名称,然后单击 Finish 。
Step 7 − On clicking Next, a New Project Wizard opens. Here, you can type the required project name and click Finish.
Step 8 − 单击“完成”时,一个应用程序将使用提供的名称(样例)创建。在名为 application 的子程序包中,将会生成一个名为 Main.java 的程序,如下所示。
Step 8 − On clicking Finish, an application is created with the given name (sample). In the sub-package named application, a program with the name Main.java is generated as shown below.
Step 9 − 该自动生成的程序包含用于生成一个空 JavaFX 窗口的代码。右键单击该文件,选择 Run As → Java Application ,如下面的屏幕截图所示。
Step 9 − This automatically generated program contains the code to generate an empty JavaFX window. Right-click on this file, select Run As → Java Application as shown in the following screenshot.
在执行该应用程序时,它会为你提供一个空 JavaFX 窗口,如下所示。
On executing this application, it gives you an empty JavaFX window as shown below.
Note − 我们将在后面的章节中详细讨论代码。
Note − We will discuss more about the code in the later chapters.
JavaFX - Architecture
JavaFX 提供了一个完整的 API,其中包含丰富的类和接口,以利用丰富的图形构建 GUI 应用程序。该 API 的重要程序包是 −
JavaFX provides a complete API with a rich set of classes and interfaces to build GUI applications with rich graphics. The important packages of this API are −
-
javafx.animation − Contains classes to add transition based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes.
-
javafx.application − Contains a set of classes responsible for the JavaFX application life cycle.
-
javafx.css − Contains classes to add CSS–like styling to JavaFX GUI applications.
-
javafx.event − Contains classes and interfaces to deliver and handle JavaFX events.
-
javafx.geometry − Contains classes to define 2D objects and perform operations on them.
-
javafx.stage − This package holds the top level container classes for JavaFX application.
-
javafx.scene − This package provides classes and interfaces to support the scene graph. In addition, it also provides sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. There are several components that support this rich API of JavaFX.
以下插图显示了 JavaFX API 的架构。在此,您可以看到支持 JavaFX API 的组件。
The following illustration shows the architecture of JavaFX API. Here you can see the components that support JavaFX API.
Scene Graph
在 JavaFX 中,GUI 应用程序使用场景图进行编码。场景图是 GUI 应用程序构建的起始点。它包含被称为节点的 (GUI) 应用程序基础元素。
In JavaFX, the GUI Applications were coded using a Scene Graph. A Scene Graph is the starting point of the construction of the GUI Application. It holds the (GUI) application primitives that are termed as nodes.
节点是视觉/图形对象,它可能包括 −
A node is a visual/graphical object and it may include −
-
*Geometrical (Graphical) objects * − (2D and 3D) such as circle, rectangle, polygon, etc.
-
UI controls − such as Button, Checkbox, Choice box, Text Area, etc.
-
Containers − (layout panes) such as Border Pane, Grid Pane, Flow Pane, etc.
-
Media elements − such as audio, video and image objects.
通常,节点集合组成一个场景图。所有这些节点按层次顺序排列,如下所示。
In general, a collection of nodes makes a scene graph. All these nodes are arranged in a hierarchical order as shown below.
场景图中的每个节点都有一个父节点,且不包含任何父节点的节点被称为 root node 。
Each node in the scene graph has a single parent, and the node which does not contain any parents is known as the root node.
同样,每个节点都必须一个或多个子级,没有子级的节点叫做 leaf node ;有子级的节点叫做 branch node 。
In the same way, every node has one or more children, and the node without children is termed as leaf node; a node with children is termed as a branch node.
一个节点实例只能添加到一个场景图一次。一个场景图的节点可以拥有效果、不透明度、变换、事件处理程序、事件处理程序、应用程序特定状态。
A node instance can be added to a scene graph only once. The nodes of a scene graph can have Effects, Opacity, Transforms, Event Handlers, Event Handlers, Application Specific States.
Prism
Prism 是一个 high performance hardware–accelerated graphical pipeline ,用于在 JavaFX 中渲染图形。它能渲染 2-D 和 3-D 图形。
Prism is a high performance hardware–accelerated graphical pipeline that is used to render the graphics in JavaFX. It can render both 2-D and 3-D graphics.
要渲染图形,Prism 会使用:
To render graphics, a Prism uses −
-
DirectX 9 on Windows XP and Vista.
-
DirectX 11 on Windows 7.
-
OpenGL on Mac and Linux, Embedded Systems.
如果系统上图形硬件支持不足,则 Prism 会使用软件渲染路径处理图形。
In case the hardware support for graphics on the system is not sufficient, then Prism uses the software render path to process the graphics.
如果与受支持的显卡或 GPU 搭配使用,它会提供更流畅的图形。但如果系统不支持显卡,则 Prism 会默认使用软件渲染堆栈(上述两个之一)。
When used with a supported Graphic Card or GPU, it offers smoother graphics. Just in case the system does not support a graphic card, then Prism defaults to the software rendering stack (either of the above two).
GWT (Glass Windowing Toolkit)
顾名思义,GWT 提供管理 Windows、计时器、表面和事件队列的服务。GWT 将 JavaFX 平台连接到本地操作系统。
As the name suggests, GWT provides services to manage Windows, Timers, Surfaces and Event Queues. GWT connects the JavaFX Platform to the Native Operating System.
Quantum Toolkit
它是对 Prism、Glass、媒体引擎和 Web 引擎的底层组件的抽象。它将 Prism 和 GWT 联系在一起,让它们可用于 JavaFX。
It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web Engine. It ties Prism and GWT together and makes them available to JavaFX.
WebView
使用 JavaFX,你还可以将 HTML 内容嵌入到场景图中。WebView 是 JavaFX 的组件,用于处理此内容。它使用一种称为 Web Kit 的技术,这是一个内部开源网络浏览器引擎。此组件支持 HTML5、CSS、JavaScript、DOM 和 SVG 等不同的 Web 技术。
Using JavaFX, you can also embed HTML content in to a scene graph. WebView is the component of JavaFX which is used to process this content. It uses a technology called Web Kit, which is an internal open-source web browser engine. This component supports different web technologies like HTML5, CSS, JavaScript, DOM and SVG.
使用 WebView,你可以:
Using WebView, you can −
-
Render HTML content from local or remote URL.
-
Support history and provide Back and Forward navigation.
-
Reload the content.
-
Apply effects to the web component.
-
Edit the HTML content.
-
Execute JavaScript commands.
-
Handle events.
通常,你可以使用 WebView 从 Java 控制 Web 内容。
In general, using WebView, you can control web content from Java.
Media Engine
JavaFX media engine 基于一个名为 Streamer 的开源引擎。此媒体引擎支持视频和音频内容的播放。
The JavaFX media engine is based on an open-source engine known as a Streamer. This media engine supports the playback of video and audio content.
JavaFX 媒体引擎为以下文件格式提供的音频支持:
The JavaFX media engine provides support for audio for the following file formats −
Audio |
MP3WAVAIFF |
Video |
FLV |
javafx.scene.media 包含 JavaFX 中提供媒体功能的类和接口。它以三个组件的形式提供,如下所示:
The package javafx.scene.media contains the classes and interfaces to provide media functionality in JavaFX. It is provided in the form of three components, which are −
-
Media Object − This represents a media file
-
Media Player − To play media content.
-
Media View − To display media.
JavaFX - Application
在本章中,我们将详细讨论 JavaFX 应用程序的结构,并通过示例学习如何创建 JavaFX 应用程序。
In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example.
JavaFX Application Structure
一般而言,JavaFX 应用程序将具有三个主要组件,即 Stage, Scene 和 Nodes ,如下所示。
In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram.
Stage
一个舞台(窗口)包含 JavaFX 应用程序的所有对象。它由包 javafx.stage 的 Stage 类表示。主舞台由平台自身创建。创建的舞台对象作为 Application 类的 start() 方法的参数传递(在下一节中说明)。
A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section).
舞台有两个确定其位置的参数,即 Width 和 Height 。它分为内容区和装饰(标题栏和边框)。
A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders).
有五种类型的舞台可用 −
There are five types of stages available −
-
Decorated
-
Undecorated
-
Transparent
-
Unified
-
Utility
您必须调用 show() 方法以显示舞台的内容。
You have to call the show() method to display the contents of a stage.
Scene
场景表示 JavaFX 应用程序的物理内容。它包含场景图的所有内容。包 javafx.scene 的类 Scene 表示场景对象。在某个实例中,场景对象仅添加到一个舞台。
A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage.
您可以通过实例化 Scene 类来创建场景。您可以选择场景的大小,方法是将其尺寸(高度和宽度)连同 root node 一起传递给其构造函数。
You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor.
Scene Graph and Nodes
scene graph 是一个树状数据结构(分层),表示场景的内容。相比之下, node 是场景图的可视/图形对象。
A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph.
节点可能包括 −
A node may include −
-
Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
-
UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
-
Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
-
Media elements such as Audio, Video and Image Objects.
包 javafx.scene 的 Node 类表示 JavaFX 中的一个节点,这个类是所有节点的超类。
The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes.
如前所述,节点有三种类型 −
As discussed earlier a node is of three types −
-
Root Node − The first Scene Graph is known as the Root node.
-
Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types − Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. WebView − This node manages the web engine and displays its contents.
-
Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
必须将根节点传递到场景图。如果将组传递为根,则所有节点都将剪切到场景,场景大小的任何更改都不会影响场景的布局。
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.
Creating a JavaFX Application
要创建 JavaFX 应用程序,你需要实例化应用程序类并实现其抽象方法 start() 。在此方法中,我们将为 JavaFX 应用程序编写代码。
To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application.
Application Class
包 javafx.application 中的 Application 类是 JavaFX 中应用程序的入口点。要创建 JavaFX 应用程序,你需要继承该类并实现其抽象方法 start() 。在此方法中,你需要编写用于 JavaFX 图形的全部代码
The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics
在 main 方法中,你必须使用 launch() 方法启动应用程序。此方法在内部调用 Application 类的 start() 方法,如下所示:
In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program.
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
/*
Code for JavaFX application.
(Stage, scene, scene graph)
*/
}
public static void main(String args[]){
launch(args);
}
}
要在 start() 方法中创建典型的 JavaFX 应用程序,你需要执行以下步骤:
Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below −
-
Prepare a scene graph with the required nodes.
-
Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.
-
Prepare a stage and add the scene to the stage and display the contents of the stage.
Preparing the Scene Graph
根据你的应用程序,你需要使用必需的节点准备一个场景图。由于根节点是第一个节点,因此你需要创建一个根节点。作为根节点,你可以从 Group, Region or WebView 中选择。
As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView.
Group − 一个 Group 节点由名称为 Group 的类表示,该类属于包 javafx.scene ,你可以通过实例化此类来创建一个 Group 节点,如下所示:
Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below.
Group root = new Group();
getChildren() 方法 Group 类提供一个 ObservableList 类的对象,保存节点。我们可以检索该对象,并将节点添加到其中,如下所示。
The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below.
//Retrieving the observable list object
ObservableList list = root.getChildren();
//Setting the text object as a node
list.add(NodeObject);
我们还可以通过在实例化时将节点对象传递给 Group 类及其构造函数来向组添加节点对象,如下所示。
We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below.
Group root = new Group(NodeObject);
Region − 这是所有基于 JavaFX Node 的 UI 控件的基类,例如 −
Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −
-
Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart. This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX. You can use these classes to embed charts in your application.
-
Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout. You can use these classes to insert predefined layouts in your application.
-
Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control. You can use these classes to insert various UI elements in your application.
在组中,您可以实例化上述任何类,并将其用作根节点,如下面的程序所示。
In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program.
//Creating a Stack Pane
StackPane pane = new StackPane();
//Adding text area to the pane
ObservableList list = pane.getChildren();
list.add(NodeObject);
WebView − 此节点管理 Web 引擎并显示其内容。
WebView − This node manages the web engine and displays its contents.
下面是表示 JavaFX 节点类层次结构的图表。
Following is a diagram representing the node class hierarchy of JavaFX.
Preparing the Scene
JavaFX 场景将表示为程序包 javafx.scene 类的 Scene 。你可以通过实例化该类来创建场景,如下面的代码块所示。
A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following cod block.
在实例化时,必须将根对象传递给场景类的构造函数。
While instantiating, it is mandatory to pass the root object to the constructor of the scene class.
Scene scene = new Scene(root);
您还可以传递两个表示场景高度和宽度的双类型参数,如下所示。
You can also pass two parameters of double type representing the height and width of the scene as shown below.
Scene scene = new Scene(root, 600, 300);
Preparing the Stage
这是任何 JavaFX 应用程序的容器,它为应用程序提供了一个窗口。它由 javafx.stage 包的 Stage 类表示。此类的对象作为 Application 类 start() 方法的参数传递。
This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class.
使用这个对象,您可以在舞台上执行各种操作。主要是,您可以执行以下操作 −
Using this object, you can perform various operations on the stage. Primarily you can perform the following −
-
Set the title for the stage using the method setTitle().
-
Attach the scene object to the stage using the setScene() method.
-
Display the contents of the scene using the show() method as shown below.
//Setting the title to Stage.
primaryStage.setTitle("Sample application");
//Setting the scene to Stage
primaryStage.setScene(scene);
//Displaying the stage
primaryStage.show();
Lifecycle of JavaFX Application
JavaFX 应用程序类有三个生命周期方法,分别是 −
The JavaFX Application class has three life cycle methods, which are −
-
start() − The entry point method where the JavaFX graphics code is to be written.
-
stop() − An empty method which can be overridden, here you can write the logic to stop the application.
-
init() − An empty method which can be overridden, but you cannot create stage or scene in this method.
除了这些以外,它提供名为 launch() 的静态方法以启动 JavaFX 应用程序。
In addition to these, it provides a static method named launch() to launch JavaFX application.
由于 launch() 方法是静态的,您需要从静态上下文中(通常是 main)调用它。每当启动 JavaFX 应用程序时,将会按照(相同顺序)执行以下操作。
Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order).
-
An instance of the application class is created.
-
Init() method is called.
-
The start() method is called.
-
The launcher waits for the application to finish and calls the stop() method.
Terminating the JavaFX Application
当应用程序的最后一个窗口关闭时,JavaFX 应用程序将被隐式终止。您可以通过将布尔值“False”传递给静态方法* setImplicitExit()*(应从静态上下文中调用)来关闭此行为。
When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method * setImplicitExit()* (should be called from a static context).
您可以使用 * Platform.exit()* 或 * System.exit*(int) 方法显式终止 JavaFX 应用程序。
You can terminate a JavaFX application explicitly using the methods * Platform.exit()* or * System.exit*(int).
Example 1 – Creating an Empty Window
此部分教您如何创建一个显示空窗口的 JavaFX 样例应用程序。以下为步骤 −
This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps −
Step 1: Creating a Class
创建一个 Java 类,继承包 javafx.application 中的类 Application ,然后实现该类的 start() 方法,如下所示。
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Step 2: Creating a Group Object
在 start() 方法中,通过实例化属于包 javafx.scene 的名为 Group 的类创建一个组对象,如下所示。
In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows.
Group root = new Group();
Step 3: Creating a Scene Object
通过实例化属于包 javafx.scene 的名为 Scene 的类,创建一个 Scene。向此类传递在上一步中创建的 Group 对象 (root) 。
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
除了根对象以外,您还可以将表示高度和宽度的两个双精度参数与 Group 类的对象一起传递,如下所示。
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(root,600, 300);
Step 4: Setting the Title of the Stage
您可以使用 Stage 类的 setTitle() 方法设置舞台的标题。 primaryStage 是 Stage 对象,它作为参数传递给场景类的 start 方法。
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
使用 primaryStage 对象,将场景的标题设置为 Sample Application ,如下所示。
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");
Step 5: Adding Scene to the Stage
您可以使用名为 Stage 的类的 setScene() 方法,将 Scene 对象添加到舞台。使用此方法添加在之前的步骤中准备的 Scene 对象,如下所示。
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below.
primaryStage.setScene(scene);
Step 6: Displaying the Contents of the Stage
使用 Stage 类的名为 show() 的方法显示场景的内容,如下所示。
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Step 7: Launching the Application
通过从 main 方法以如下方式调用 Application 类的静态方法 launch() 启动 JavaFX 应用程序。
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Example
以下程序生成一个空 JavaFX 窗口。将此代码保存在名为 JavafxSample.java 的文件中
The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();
//Creating a Scene by passing the group object, height and width
Scene scene = new Scene(group ,600, 300);
//setting color to the scene
scene.setFill(Color.BROWN);
//Setting the title to Stage.
primaryStage.setTitle("Sample Application");
//Adding the scene to Stage
primaryStage.setScene(scene);
//Displaying the contents of the stage
primaryStage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac JavafxSample.java
java JavafxSample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Example 2 – Drawing a Straight Line
在前面的示例中,我们已经看到了如何创建空界面。在这个示例中,让我们使用 JavaFX 库尝试绘制一条直线。
In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library.
以下为步骤 −
Following are the steps −
Step 1: Creating a Class
创建一个 Java 类并继承包 javafx.application 的 Application 类,并按如下方式实现此类的 start() 方法。
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class DrawingLine extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Step 2: Creating a Line
你可以通过实例化名为 Line 的类并在 javafx.scene.shape 程序包中进行实例化来在 JavaFX 中创建一条线,如下所示实例化该类。
You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows.
//Creating a line object
Line line = new Line();
Step 3: Setting Properties to the Line
通过使用各自的 setter 方法来设置 startX, startY, endX 和 endY 属性,指定坐标以在 X-Y 平面中绘制线,如下面的代码块所示。
Specify the coordinates to draw the line on an X-Y plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block.
line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);
Step 4: Creating a Group Object
在 start() 方法中,通过实例化名为 Group 的类来创建一个组对象,该类属于 javafx.scene 程序包。
In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
将上一步中创建的 Line(节点)对象作为 Group 类的构造函数的一个参数,以便将其添加到组中,如下所示 −
Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(line);
Step 5: Creating a Scene Object
通过实例化名为 Scene 的类并在 javafx.scene 程序包中进行实例化来创建 Scene。该类将传递上一步中创建的 Group 对象 (root) 。
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) that was created in the previous step.
除了根对象以外,您还可以将表示高度和宽度的两个双精度参数与 Group 类的对象一起传递,如下所示。
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);
Step 6: Setting the Title of the Stage
您可以使用 Stage 类的 setTitle() 方法设置舞台的标题。 primaryStage 是 Stage 对象,它作为参数传递给场景类的 start 方法。
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
使用 primaryStage 对象,将场景的标题设置为 Sample Application ,如下所示。
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");
Step 7: Adding Scene to the Stage
你可以使用名为 Stage 的类的 setScene() 方法将 Scene 对象添加到舞台。使用该方法添加在之前的步骤中准备好的 Scene 对象,如下所示。
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);
Step 8: Displaying the Contents of the Stage
使用 Stage 类的名为 show() 的方法显示场景的内容,如下所示。
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Step 9: Launching the Application
通过从 main 方法以如下方式调用 Application 类的静态方法 launch() 启动 JavaFX 应用程序。
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Example
下面的程序展示了如何使用 JavaFX 生成一条直线。将此代码保存在一个名为 JavafxSample.java 的文件中。
The following program shows how to generate a straight line using JavaFX. Save this code in a file with the name JavafxSample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class DrawingLine extends Application{
@Override
public void start(Stage stage) {
//Creating a line object
Line line = new Line();
//Setting the properties to a line
line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);
//Creating a Group
Group root = new Group(line);
//Creating a Scene
Scene scene = new Scene(root, 600, 300);
//Setting title to the scene
stage.setTitle("Sample application");
//Adding the scene to the stage
stage.setScene(scene);
//Displaying the contents of a scene
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac DrawingLine.java
java DrawingLine
执行时,上述程序生成一个 JavaFX 窗口,显示一条直线,如下所示。
On executing, the above program generates a JavaFX window displaying a straight line as shown below.
Example 3 – Displaying Text
我们也可以在 JavaFX 场景中嵌入文本。此示例展示如何在 JavaFX 中嵌入文本。
We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX.
以下为步骤 −
Following are the steps −
Step 1: Creating a Class
创建 Java 类并继承包 Application 的 javafx.application 类,并按照如下方式实现此类的 start() 方法。
Create a Java Class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class DrawingLine extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Step 2: Embedding Text
您可以通过实例化属于包 javafx.scene.shape 的名为 Text 的类来将文本嵌入 JavaFX 场景,实例化该类。
You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a package javafx.scene.shape, instantiate this class.
您可以通过以字符串格式传递要嵌入的文本来实例化此类。或者,您可以使用默认构造函数创建文本对象,如下所示。
You can instantiate this class by passing text to be embedded, in String format Or, you can create text object using the default constructor as shown below.
//Creating a Text object
Text text = new Text();
Step 3: Setting the Font
您可以使用 Text 类的 setFont() 方法为文本设置字体。此方法接受字体对象作为参数。将给定文本的字体设置为 45,如下所示。
You can set font to the text using the setFont() method of the Text class. This method accepts a font object as parameters. Set the font of the given text to 45 as shown below.
//Setting font to the text
text.setFont(new Font(45));
Step 4: Setting the Position of the Text
您可以使用各自的 setter 方法 setX() 和 setY() 设置文本在 X-Y 平面上的位置,方法是设置 X 和 Y 坐标,如下所示。
You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective setter methods setX() and setY() as follows.
//setting the position of the text
text.setX(50);
text.setY(150);
Step 5: Setting the text to be added
您可以使用文本类的 setText() 方法设置要添加的文本。此方法接受一个字符串参数,该字符串表示要添加的文本。
You can set the text to be added using the setText() method of the Text class. This method accepts a string parameter representing the text to be added.
text.setText("Welcome to Tutorialspoint");
Step 6: Creating a Group Object
在 start() 方法中,通过实例化属于包 javafx.scene 的名为 Group 的类来创建组对象。
In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
将上一步创建的 Text(节点)对象作为参数传递给 Group 类的构造函数,以便将其添加到组中,如下所示 −
Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(text)
Step 7: Creating a Scene Object
通过实例化属于包 javafx.scene 的名为 Scene 的类,创建一个 Scene。向此类传递在上一步中创建的 Group 对象 (root) 。
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
除了根对象以外,您还可以将表示高度和宽度的两个双精度参数与 Group 类的对象一起传递,如下所示。
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);
Step 8: Setting the Title of the Stage
您可以使用 Stage 类的 setTitle() 方法设置舞台的标题。 primaryStage 是 Stage 对象,它作为参数传递给场景类的 start 方法。
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
使用 primaryStage 对象,将场景的标题设置为 Sample Application ,如下所示。
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");
Step 9: Adding Scene to the Stage
你可以使用名为 Stage 的类的 setScene() 方法将 Scene 对象添加到舞台。使用该方法添加在之前的步骤中准备好的 Scene 对象,如下所示。
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);
Step 10: Displaying the Contents of the Stage
使用 Stage 类的名为 show() 的方法显示场景的内容,如下所示。
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Step 11: Launching the Application
通过从 main 方法以如下方式调用 Application 类的静态方法 launch() 启动 JavaFX 应用程序。
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Example
以下是使用 JavaFX 显示文本的程序。将此代码保存在名为 DisplayingText.java 的文件中。
Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class DisplayingText extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(new Font(45));
//setting the position of the text
text.setX(50);
text.setY(150);
//Setting the text to be added.
text.setText("Welcome to Tutorialspoint");
//Creating a Group object
Group root = new Group();
//Retrieving the observable list object
ObservableList list = root.getChildren();
//Setting the text object as a node to the group object
list.add(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Sample Application");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac DisplayingText.java
java DisplayingText
执行时,上述程序生成一个 JavaFX 窗口,显示文本,如下所示。
On executing, the above program generates a JavaFX window displaying text as shown below.
JavaFX - 2D Shapes
在上一章中,我们看到了 JavaFX 的基本应用,其中我们学会了如何创建一个空窗口以及如何在 JavaFX 的 XY 平面上绘制线。除了线以外,我们还可以绘制其他一些 2D 形状。
In the previous chapter, we have seen the basic application of JavaFX, where we learnt how to create an empty window and how to draw a line on an XY plane of JavaFX. In addition to the line, we can also draw several other 2D shapes.
2D Shape
通常,2D 形状是可以绘制在 XY 平面上的几何图形,包括线、矩形、圆等。
In general, a 2D shape is a geometrical figure that can be drawn on the XY plane, these include Line, Rectangle, Circle, etc.
使用 JavaFX 库,你可以绘制:
Using the JavaFX library, you can draw −
-
Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc.
-
Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc.
-
In addition to these, you can also draw a 2D shape by parsing SVG path.
每个上述 2D 形状均用一个类表示,所有这些类都属于包 javafx.scene.shape 。名为 Shape 的类是 JavaFX 中所有二维形状的基类。
Each of the above mentioned 2D shape is represented by a class and all these classes belongs to the package javafx.scene.shape. The class named Shape is the base class of all the 2-Dimensional shapes in JavaFX.
Creating a 2D Shape
要创建图表,你需要:
To create a chart, you need to −
-
Instantiate the respective class of the required shape.
-
Set the properties of the shape.
-
Add the shape object to the group.
Instantiating the Respective Class
要创建一个 2 维图形,首先需要实例化其各自的类。
To create a 2 Dimensional shape, first of all you need to instantiate its respective class.
例如,如果您要创建一条线,则需要实例化名为 Line 的类,如下所示 −
For example, if you want to create a line you need to instantiate the class named Line as follows −
Line line = new Line();
Setting the Properties of the Shape
实例化该类后,你需要使用 setter 方法为该形状设置属性。
After instantiating the class, you need to set the properties for the shape using the setter methods.
例如,要绘制一条线,您需要传递其起点和终点的 x 和 y 坐标。您可以使用它们各自的 setter 方法指定这些值,如下所示 −
For example, to draw a line you need to pass its x and y coordinates of the start point and end point of the line. You can specify these values using their respective setter methods as follows −
//Setting the Properties of the Line
line.setStartX(150.0f);
line.setStartY(140.0f);
line.setEndX(450.0f);
line.setEndY(140.0f);
Adding the Shape Object to the Group
最后,你需要将形状的对象添加到组中,方法是将其作为构造函数的参数进行传递,如下所示。
Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below.
//Creating a Group object
Group root = new Group(line);
下表列出了 JavaFX 提供的各种形状(类)。
The following table gives you the list of various shapes (classes) provided by JavaFX.
S.No |
Shape & Description |
1 |
LineA line is a geometrical structure joining two point. The Line class of the package javafx.scene.shape represents a line in the XY plane. |
2 |
RectangleIn general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles. In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape. |
3 |
Rounded RectangleIn JavaFX, you can draw a rectangle either with sharp edges or with arched edges and The one with arched edges is known as a rounded rectangle. |
4 |
CircleA circle is a line forming a closed loop, every point on which is a fixed distance from a centre point. In JavaFX, a circle is represented by a class named Circle. This class belongs to the package javafx.scene.shape. |
5 |
EllipseAn ellipse is defined by two points, each called a focus. If any point on the ellipse is taken, the sum of the distances to the focus points is constant. The size of the ellipse is determined by the sum of these two distances. In JavaFX, an ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape. |
6 |
PolygonA closed shape formed by a number of coplanar line segments connected end to end. In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. |
7 |
PolylineA polyline is same a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments. In JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. |
8 |
Cubic CurveA cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape. |
9 |
QuadCurveA quadratic curve is a Bezier parametric curve in the XY plane is a curve of degree 2. In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape. |
10 |
ArcAn arc is part of a curve. In JavaFX, an arc is represented by a class named Arc. This class belongs to the package − javafx.scene.shape. Types Of ArcIn addition to this we can draw three types of arc’s Open, Chord, Round. |
11 |
SVGPathIn JavaFX, we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape. This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.. |
Drawing More Shapes Through Path Class
在上一节中,我们已经看到了如何通过实例化类和设置相应参数来绘制一些简单的预定义形状。
In the previous section, we have seen how to draw some simple predefined shapes by instantiating classes and setting respective parameters.
但是,仅靠这些预定义形状还不足以构建 javafx.shape package 提供的基本图形以外的更复杂的形状。
But, just these predefined shapes are not sufficient to build complexer shapes other than the primitives provided by the javafx.shape package.
例如,如果您想要绘制一个如以下图表所示的图形元素,则不能依赖于那些简单的形状。
For example, if you want to draw a graphical element as shown in the following diagram, you cannot rely on those simple shapes.
The Path Class
为了绘制这种复杂结构,JavaFX 提供了一个名为 Path 的类。此类表示形状的几何轮廓。
To draw such complex structures JavaFX provides a class named Path. This class represents the geometrical outline of a shape.
它附加到一个可观察列表,其中包含各种 Path Elements ,如 moveTo、LineTo、HlineTo、VlineTo、ArcTo、QuadCurveTo、CubicCurveTo。
It is attached to an observable list which holds various Path Elements such as moveTo, LineTo, HlineTo, VlineTo, ArcTo, QuadCurveTo, CubicCurveTo.
在实例化时,此类基于给定的路径元素构造一个路径。
On instantiating, this class constructs a path based on the given path elements.
您可以在实例化此类时向其传递路径元素,如下所示:
You can pass the path elements to this class while instantiating it as follows−
Path myshape = new Path(pathElement1, pathElement2, pathElement3);
或者,您可以获取可观察列表,并使用 addAll() 方法添加所有路径元素,如下所示:
Or, you can get the observable list and add all the path elements using addAll() method as follows −
Path myshape = new Path();
myshape.getElements().addAll(pathElement1, pathElement2, pathElement3);
您还可以使用 add() 方法逐个添加元素,如下所示:
You can also add elements individually using the add() method as −
Path myshape = new Path();
myshape.getElements().add(pathElement1);
The Move to Path Element
路径元素 MoveTo 用于将路径的当前位置移动到指定点。它通常用于设置使用路径元素绘制的形状的起点。
The Path Element MoveTo is used to move the current position of the path to a specified point. It is generally used to set the starting point of a shape drawn using the path elements.
它由包 javafx.scene.shape 中名为 LineTo 的类表示。它具有双精度数据类型2个属性,即:_
It is represented by a class named LineTo of the package javafx.scene.shape. It has 2 properties of the double datatype namely −
-
X − The x coordinate of the point to which a line is to be drawn from the current position.
-
Y − The y coordinate of the point to which a line is to be drawn from the current position.
您可以通过实例化MoveTo类并传递新点的x、y坐标来创建移动到路径元素,如下所示:_
You can create a move to path element by instantiating the MoveTo class and passing the x, y coordinates of the new point as follows −
MoveTo moveTo = new MoveTo(x, y);
如果您不向构造函数传递任何值,则新点将被设置为(0,0)。
If you don’t pass any values to the constructor, then the new point will be set to (0,0).
您还可以使用各自的setter方法设置x,y坐标的值,如下所示:_
You can also set values to the x, y coordinate, using their respective setter methods as follows −
setX(value);
setY(value);
Example – Drawing a Complex Path
在此示例中,我们将展示如何使用 Path, MoveTo 和 Line 类绘制以下形状。
In this example, we will show how to draw the following shape using the Path, MoveTo and Line classes.
将此代码存储在名称为 ComplexShape.java 的文件中。
Save this code in a file with the name ComplexShape.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
public class ComplexShape extends Application {
@Override
public void start(Stage stage) {
//Creating a Path
Path path = new Path();
//Moving to the starting point
MoveTo moveTo = new MoveTo(108, 71);
//Creating 1st line
LineTo line1 = new LineTo(321, 161);
//Creating 2nd line
LineTo line2 = new LineTo(126,232);
//Creating 3rd line
LineTo line3 = new LineTo(232,52);
//Creating 4th line
LineTo line4 = new LineTo(269, 250);
//Creating 4th line
LineTo line5 = new LineTo(108, 71);
//Adding all the elements to the path
path.getElements().add(moveTo);
path.getElements().addAll(line1, line2, line3, line4, line5);
//Creating a Group object
Group root = new Group(path);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing an arc through a path");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac ComplexShape.java
java ComplexShape
在执行时,上述程序会生成一个 JavaFX 窗口,显示一条从当前位置绘制到指定点的弧,如下所示。
On executing, the above program generates a JavaFX window displaying an arc, which is drawn from the current position to the specified point as shown below.
以下是由JavaFX提供的各种路径元素(类)。这些类存在于包 javafx.shape 中。所有这些类都继承了类 PathElement 。
Following are the various path elements (classes) provided by JavaFX. These classes exist in the package javafx.shape. All these classes inherit the class PathElement.
S.No |
Shape & Description |
1 |
LineToThe path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape. |
2 |
HlineToThe path element HLineTo is used to draw a horizontal line to a point in the specified coordinates from the current position. It is represented by a class named HLineTo. This class belongs to the package javafx.scene.shape. |
3 |
VLineToThe path element vertical line is used to draw a vertical line to a point in the specified coordinates from the current position. It is represented by a class named VLineTo. This class belongs to the package javafx.scene.shape. |
4 |
QuadCurveToThe path element quadratic curve is used to draw a quadratic curve to a point in the specified coordinates from the current position. It is represented by a class named QuadraticCurveTo. This class belongs to the package javafx.scene.shape. |
5 |
CubicCurveToThe path element cubic curve is used to draw a cubic curve to a point in the specified coordinates from the current position. It is represented by a class named CubicCurveTo. This class belongs to the package javafx.scene.shape. |
6 |
ArcToThe path element Arc is used to draw an arc to a point in the specified coordinates from the current position. It is represented by a class named ArcTo. This class belongs to the package javafx.scene.shape. |
Properties of 2D Objects
对于所有 2 维度对象,你可以设置各种属性,如填充、描边、描边类型等。下一节将讨论 2D 对象的各种属性。
For all the 2-Dimensional objects, you can set various properties like fill, stroke, StrokeType, etc. The following section discusses various properties of 2D objects.
Operations on 2D Objects
如果我们向一个组中添加多个形状,第一个形状就会被第二个形状重叠,如下所示。
If we add more than one shape to a group, the first shape is overlapped by the second one as shown below.
除了变换(旋转、比例缩放、平移等)、转换(动画)之外,您还可以在 2D 对象上执行三个操作: Union, Subtraction 和 Intersection 。
In addition to the transformations (rotate, scale, translate, etc.), transitions (animations), you can also perform three operations on 2D objects namely – Union, Subtraction and Intersection.
S.No |
Operation & Description |
1 |
Union OperationThis operation takes two or more shapes as inputs and returns the area occupied by them. |
2 |
Intersection OperationThis operation takes two or more shapes as inputs and returns the intersection area between them. |
3 |
Subtraction OperationThis operation takes two or more shapes as an input. Then, it returns the area of the first shape excluding the area overlapped by the second one. |
JavaFX - Text
就像各种形状一样,您还可以在 JavaFX 中创建文本节点。文本节点由名为 Text 的类表示,此类属于 javafx.scene.text 包。
Just like various shapes, you can also create a text node in JavaFX. The text node is represented by the class named Text, which belongs to the package javafx.scene.text.
此类包含几个属性,用于在 JavaFX 中创建文本并修改其外观。此类还继承属于 javafx.scene.shape 包的 Shape 类。
This class contains several properties to create text in JavaFX and modify its appearance. This class also inherits the Shape class which belongs to the package javafx.scene.shape.
因此,除了字体、对齐方式、行距、文本等文本属性外,它还继承了基本的形状节点属性,如 strokeFill, stroke, strokeWidth, strokeType, 等。
Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc. It also inherits the basic shape node properties such as strokeFill, stroke, strokeWidth, strokeType, etc.
Creating a Text Node
由于包 javafx.scene.text 的 Text 类表示 JavaFX 中的文本节点,因此您可以通过如下所示实例化此类来创建文本 -
Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you can create a text by instantiating this class as follows −
Text text = new Text();
Text 类包含一个名为 text 的字符串类型属性,它表示要创建的文本。
The class Text contains a property named text of string type, which represents the text that is to be created.
实例化 Text 类后,需要使用 setText() 方法为该属性设置值,如下所示。
After instantiating the Text class, you need to set value to this property using the setText() method as shown below.
String text = "Hello how are you"
Text.setText(text);
您还可以通过使用各自的设置器方法,即 setX() 和 setY() ,为 x 和 y 指定值来设置文本的位置(原点),如下面的代码块所示 -
You can also set the position (origin) of the text by specifying the values to the properties x and y using their respective setter methods namely setX() and setY() as shown in the following code block −
text.setX(50);
text.setY(50);
Example
以下程序是一个示例,展示了如何在 JavaFX 中创建文本节点。将此代码保存在名为 TextExample.java 的文件中。
The following program is an example demonstrating how to create a text node in JavaFX. Save this code in a file with name TextExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Text;
public class TextExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting the text to be added.
text.setText("Hello how are you");
//setting the position of the text
text.setX(50);
text.setY(50);
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Sample Application");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac TextExample.java
java TextExample
执行时,上述程序会生成一个 JavaFX 窗口,其中显示指定的文本,如下所示 -
On executing, the above program generates a JavaFX window displaying the specified text as follows −
Position and Font of the Text
默认情况下,由文本类创建的文本的字体为…、大小为…,颜色为黑色。
By default, the text created by text class is of the font…, size…, and black in color.
您可以使用 setFont() 方法更改文本的字体大小和颜色。此方法接受 Font 类的对象。
You can change the font size and color of the text using the setFont() method. This method accepts an object of the Font class.
包 javafx.scene.text 中名为 Font 的类用于定义文本的字体。此类包含一个名为 font() 的静态方法。
The class named Font of the package javafx.scene.text is used to define the font for the text. This class contains a static method named font().
此方法接受四个参数,即:
This method accepts four parameters namely −
-
family − This is of a String type and represents the family of the font that we want to apply to the text.
-
weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN.
-
posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC.
-
size − This property is of type double and it represents the size of the font.
您可以使用以下方法将字体设置为文本 −
You can set font to the text by using the following method −
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
Example
以下程序是一个示例,展示了如何在 JavaFX 中设置文本节点的字体。在这里,我们设置字体为 Verdana,粗细为粗体,姿势为常规,大小为 20。
The following program is an example demonstrating how to set font of the text node in JavaFX. In here, we are setting the font to Verdana, weight to bold, posture to regular and size to 20.
将此代码保存在一个名为 TextFontExample.java 的文件中。
Save this code in a file with the name TextFontExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class TextFontExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text.setX(50);
text.setY(130);
//Setting the text to be added.
text.setText("Hi how are you");
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Setting Font to the text");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac TextFontExample.java
java TextFontExample
执行后,上述程序会生成一个 JavaFX 窗口,显示具有指定字体的文本,如下所示 −
On executing, the above program generates a JavaFX window displaying the text with the specified font as follows −
Stroke and Color
文本类还继承了包的形状类。因此,您可以使用 javafx.scene.shape 来为文本节点设置笔划和颜色。
The Text class also inherits the class Shape of the package. Therefore, you can use javafx.scene.shape with which you can set the stroke and color to the text node too.
您可以按照以下方式使用形状(继承)类的 setFill() 方法将颜色设置为文本 −
You can set the color to the text using the setFill() method of the shape (inherited) class as follows −
text.setFill(Color.BEIGE);
同样,您可以使用 setStroke() 方法设置文本的描边颜色。而描边的宽度可以使用 setStrokeWidth() 方法设置,如下所示 −
Similarly, you can set the stroke color of the text using the method setStroke(). While the width of the stroke can be set using the method setStrokeWidth() as follows −
//Setting the color
text.setFill(Color.BROWN);
//Setting the Stroke
text.setStrokeWidth(2);
//Setting the stroke color
text.setStroke(Color.BLUE);
Example
下面的程序是一个示例,展示如何设置文本节点的颜色、strokeWidth 和 strokeColor。在此代码中,我们将描边颜色设置为蓝色,文本颜色设置为棕色,描边宽度设置为 2。
The following program is an example that demonstrates how to set the color, strokeWidth and strokeColor, of the text node. In this code, we are setting stroke color to – blue, text color to – brown and the stroke width to – 2.
将此代码保存在一个名为 StrokeExample.java 的文件中。
Save this code in a file with the name StrokeExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class StrokeExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 50));
//setting the position of the text
text.setX(50);
text.setY(130);
//Setting the color
text.setFill(Color.BROWN);
//Setting the Stroke
text.setStrokeWidth(2);
// Setting the stroke color
text.setStroke(Color.BLUE);
//Setting the text to be added.
text.setText("Hi how are you");
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Setting font to the text");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac StrokeExample.java
java StrokeExample
执行上述程序时,会生成一个 JavaFX 窗口,其按如下方式显示具有指定描边和颜色属性的文本:
On executing, the above program generates a JavaFX window displaying the text with the specified stroke and color attributes as follows −
Applying Decorations to Text
您还可以应用装饰,例如删除线;在这种情况下,会在文本中划一条线。可以使用 Text 类的函数下划线文本。
You can also apply decorations such as strike through; in which case a line is passed through the text. You can underline a text using the methods of the Text class.
您可以使用 setStrikethrough() 方法在文本中加删除线。该方法接受布尔值,向该方法传递值 true 会在文本中加删除线,如以下代码框所示:
You can strike through the text using the method setStrikethrough(). This accepts a Boolean value, pass the value true to this method to strike through the text as shown in the following code box −
//Striking through the text
text1.setStrikethrough(true);
同理,您可以通过向方法 setUnderLine() 传递值 true 为文本添加下划线,如下所示:
In the same way, you can underline a text by passing the value true to the method setUnderLine() as follows −
//underlining the text
text2.setUnderline(true);
Example
下面的程序是一个示例,展示如何将装饰(如 underline 或 strike through )应用于文本。将此代码保存在一个名为 DecorationsExample.java 的文件中。
The following program is an example demonstrating how to apply decorations such as underline or strike through to a text. Save this code in a file with the name DecorationsExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class DecorationsExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text_Example object
Text text1 = new Text("Hi how are you");
//Setting font to the text
text1.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text1.setX(50);
text1.setY(75);
//Striking through the text
text1.setStrikethrough(true);
//Creating a Text_Example object
Text text2 = new Text("Welcome to Tutorialspoint");
//Setting font to the text
text2.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text2.setX(50);
text2.setY(150);
//underlining the text
text2.setUnderline(true);
//Creating a Group object
Group root = new Group(text1, text2);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Decorations Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令从命令提示符处编译并执行已保存的 Java 文件。
Compile and execute the saved Java file from the command prompt using the following commands.
javac DecorationsExample.java
java DecorationsExample
执行上述程序时,会生成一个 JavaFX 窗口,如下所示:
On executing, the above program generates a JavaFX window as shown below −
JavaFX - Effects
效果是任何增强图形外观的操作。在 JavaFX 中,效果是一种应用于节点以在视觉上增强其外观的算法。 Node 类的 effect 属性用于指定效果。
An effect is any action that enhances the appearance of the graphics. In JavaFX, an effect is an algorithm that is applied on nodes to enhance their appearance visually. The effect property of the Node class is used to specify the effect.
在 JavaFX 中,您可以为一个节点设置各种效果,例如 bloom, blur 和 glow 。每种这些效果都由一个类表示,所有这些类都存在于名为 javafx.scene.effect 的包中。
In JavaFX, you can set various effects to a node such as bloom, blur and glow. Each of these effects are represented by a class and all these classes are available in a package named javafx.scene.effect.
Applying Effects to a Node
您可以使用 setEffect() 方法将效果应用于节点。对于此方法,您需要传入效果对象。
You can apply an effect to a node using the setEffect() method. To this method, you need to pass the object of the effect.
要将效果应用于节点,您需要−
To apply an effect to a node, you need to −
-
Create the node.
-
Instantiate the respective class of the effect that is needed to be applied.
-
Set the properties of the effect.
-
Apply the effect to the node using the setEffect() method.
Creating the Nodes
首先,通过实例化其相应的类,在 JavaFX 应用程序中创建节点。
First of all, create the nodes in a JavaFX application by instantiating their respective classes.
例如,如果你想对应用程序中的图像应用发光效果。首先,你需要通过实例化 Image 类创建一个图像节点,并设置其视图,如下所示。
For example, if you want to apply glow effect to an image in your application. Firstly, you need to create an image node by instantiating the Image class and set its view as shown below.
//Creating an image
Image image = new Image("https://www.tutorialspoint.com/green/images/logo.png");
//Setting the image view
ImageView imageView = new ImageView(image);
//Setting the position of the image
imageView.setX(100);
imageView.setY(70);
//setting the fit height and width of the image view
imageView.setFitHeight(200);
imageView.setFitWidth(400);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
Instantiating the Respective Class
实例化表示需要应用到创建的节点的效果的类。
Instantiate the class representing the effect that is needed to be applied to the created node.
例如 − 要应用发光效果,你需要实例化 Glow 类,如下面的代码框所示 −
For example − To apply the glow effect, you need to instantiate the Glow class as shown in the following code box −
Glow glow = new Glow();
Setting the Properties of the Effect
实例化类后,你需要使用其 setter 方法为效果设置属性。
After instantiating the class, you need to set the properties for the effect using its setter methods.
例如 − 要绘制一个 3 维盒子,你需要传递其宽度、高度和深度。你可以使用它们各自的 setter 方法指定这些值,如下所示 −
For example − To draw a 3-Dimensional box, you need to pass its width, height and depth. You can specify these values using their respective setter methods as shown below −
//setting the level property
glow.setLevel(0.9);
Adding Effect to the Node
最后,你可以使用 setEffect() 方法向节点应用所需的效果。例如:要将发光效果设置到图像节点,你需要按照如下方式将 Glow 类的对象传递给该方法 −
Finally, you can apply the required effect to the node using the setEffect() method. For example: To set the glow effect to the image node, you need to pass the object of the Glow class to this method as follows −
imageView.setEffect(glow);
JavaFX Effects − 下表为你提供了 JavaFX 提供的各种效果(类)列表。这些类存在于名为 javafx.scene.effect 的包中。
JavaFX Effects − The following table gives you the list of various effects (classes) provided by JavaFX. These classes exist in the package called javafx.scene.effect.
S.No |
Shape and Description |
1 |
Color AdjustYou can adjust the color of an image by applying the color adjust effect to it. This includes the adjustment of the hue, saturation, brightness and contrast on each pixel The class named ColorAdjust of the package javafx.scene.effect represents the color adjust effect. |
2 |
Color InputColor Input Effect gives the same output as drawing a rectangle and filling it with color. Unlike other effects, if this effect is applied to any node, it displays only a rectangular box (not the node). This effect is mostly used to pass as an input for other effects. The class named ColorInput of the package javafx.scene.effect represents the color input effect. |
3 |
Image InputImage input effect in JavaFX just embeds an image to the JavaFX screen. Just like Color Input effect (It is used to pass the specified colored rectangular region as input to other effect), Image Input effect is used to pass the specified image as an input to another effect. The class named ImageInput of the package javafx.scene.effect represents the Image Input effect. |
4 |
BlendIn general, blend means mixture of two or more different things or substances. If we apply this blend effect, it takes the pixels of two different inputs, at the same location and it produces a combined output based on the blend mode. The class named Blend of the package javafx.scene.effect represents the blend effect. |
5 |
BloomOn applying bloom effect, pixels in some portions of the node are made to glow. The class named Bloom of the package javafx.scene.effect represents the bloom effect. |
6 |
GlowJust like bloom, the Glow effect makes the given input image to glow, this effect makes the bright pixels of the input brighter. The class named Glow of the package javafx.scene.effect represents the glow effect. |
7 |
Box BlurOn applying this blur effect to a node, it is made unclear. Box blur is a kind of blur effect provided by JavaFX. In this effect, when we apply blur to a node, a simple box filter is used. The class named BoxBlur of the package javafx.scene.effect represents the boxblur effect. |
8 |
GaussianBlurJust like Box Blur Gaussian is an effect to blur the nodes in JavaFX. The only difference in the Gaussian Blur effect is that a Gaussian convolution kernel is used to produce a blurring effect. The class named GaussianBlur of the package javafx.scene.effect represents the Gaussian Blur effect. |
9 |
MotionBlurJust like Gaussian Effects, Motion Blur is an effect to blur the nodes in JavaFX. It also uses a Gaussian convolution kernel to produce a blurring effect, but the difference is in this effect the Gaussian convolution kernel is used with a specified angle. The class named MotionBlur of the package javafx.scene.effect represents the Motion Blur effect. |
10 |
ReflectionOn applying the reflection effect to a node in JavaFX, a reflection of it is added at the bottom of the node. The class named Reflection of the package javafx.scene.effect represents the reflection effect. |
11 |
SepiaToneOn applying the Sepia tone effect to a node in JavaFX (image in general), it is toned with a reddish brown color. The class named SepiaTone of the package javafx.scene.effect represents the sepia tone effect. |
12 |
ShadowThis effect creates a duplicate of the specified node with blurry edges. The class named Shadow of the package javafx.scene.effect represents the sepia tone effect. |
13 |
DropShadowOn applying this effect to a node, a shadow will be created behind the specified node. The class named DropShadow of the package javafx.scene.effect represents the drop shadow effect. |
14 |
InnerShadowOn applying this effect to a node, a shadow will be created inside the edges of the node. The class named InnerShadow of the package javafx.scene.effect represents the inner shadow effect. |
15 |
LightingThe lighting effect is used to simulate a light from a light source. There are different kinds of light sources namely point, distant and spot. The class named Lighting of the package javafx.scene.effect represents the lighting effect. |
16 |
Light.DistantOn applying this effect to a node, a light is simulated on it, as if it is being generated by a distant light source. Distant Light Source − A source which is at a far distance from the node. In here, the light is attenuated in one direction from the source. The class named Light.Distant of the package javafx.scene.effect represents the distant light source. |
17 |
Light.SpotOn applying this effect to a node, a light is simulated on it, as if it is being generated by a spot light. Spot light Source − The light from this source attenuates in all directions. The intensity of the light depends on the distance of the object from the source. The class named Light.Spot of the package javafx.scene.effect represents the distant light source. |
18 |
Point.SpotOn applying this effect to a node, a light is simulated on it, as if it is being generated by a point light source. Point Light Source − The light from this source attenuates in all directions from a single point. The intensity of the light depends on the distance of the object from the source. The class named Point.Spot of the package javafx.scene.effect represents the point light. |
JavaFX - Transformations
通过应用规则,图形变形成为了改变一些图形内容。我们可以进行旋转等各种类型的变形。
Transformation means changing some graphics into something else by applying rules. We can have various types of transformations such as Translation, Scaling Up or Down, Rotation, Shearing, etc.
使用 JavaFX,可以在节点上应用旋转、缩放和平移等变换。所有这些转换都由不同的类表示,并且属于包 javafx.scene.transform 。
Using JavaFX, you can apply transformations on nodes such as rotation, scaling and translation. All these transformations are represented by various classes and these belong to the package javafx.scene.transform.
S.No |
Transformation & Description |
1 |
RotationIn rotation, we rotate the object at a particular angle θ (theta) from its origin. |
2 |
ScalingTo change the size of an object, scaling transformation is used. |
3 |
TranslationMoves an object to a different position on the screen. |
4 |
ShearingA transformation that slants the shape of an object is called the Shear Transformation. |
Multiple Transformations
你也可以在 JavaFX 中对节点应用多个转换。以下程序就是一个示例,它同时对一个矩形执行 Rotation, Scaling 和 Translation 转换。
You can also apply multiple transformations on nodes in JavaFX. The following program is an example which performs Rotation, Scaling and Translation transformations on a rectangle simultaneously.
将此代码保存在一个名为 − 的文件中
Save this code in a file with the name −
MultipleTransformationsExample.java 。
MultipleTransformationsExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
public class MultipleTransformationsExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Rectangle
Rectangle rectangle = new Rectangle(50, 50, 100, 75);
//Setting the color of the rectangle
rectangle.setFill(Color.BURLYWOOD);
//Setting the stroke color of the rectangle
rectangle.setStroke(Color.BLACK);
//creating the rotation transformation
Rotate rotate = new Rotate();
//Setting the angle for the rotation
rotate.setAngle(20);
//Setting pivot points for the rotation
rotate.setPivotX(150);
rotate.setPivotY(225);
//Creating the scale transformation
Scale scale = new Scale();
//Setting the dimensions for the transformation
scale.setX(1.5);
scale.setY(1.5);
//Setting the pivot point for the transformation
scale.setPivotX(300);
scale.setPivotY(135);
//Creating the translation transformation
Translate translate = new Translate();
//Setting the X,Y,Z coordinates to apply the translation
translate.setX(250);
translate.setY(0);
translate.setZ(0);
//Adding all the transformations to the rectangle
rectangle.getTransforms().addAll(rotate, scale, translate);
//Creating a Group object
Group root = new Group(rectangle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Multiple transformations");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac MultipleTransformationsExample.java
java MultipleTransformationsExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Transformations on 3D Objects
你还可以对三维对象执行变换。以下是一个旋转并平移一个三维盒子的示例。
You can also apply transformations on 3D objects. Following is an example which rotates and translates a 3-Dimensional box.
将此代码保存在名为 RotationExample3D.java 的文件中。
Save this code in a file with the name RotationExample3D.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
public class RotationExample3D extends Application {
@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();
//Setting the properties of the Box
box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(150.0);
//Creating the translation transformation
Translate translate = new Translate();
translate.setX(400);
translate.setY(150);
translate.setZ(25);
Rotate rxBox = new Rotate(0, 0, 0, 0, Rotate.X_AXIS);
Rotate ryBox = new Rotate(0, 0, 0, 0, Rotate.Y_AXIS);
Rotate rzBox = new Rotate(0, 0, 0, 0, Rotate.Z_AXIS);
rxBox.setAngle(30);
ryBox.setAngle(50);
rzBox.setAngle(30);
box.getTransforms().addAll(translate,rxBox, ryBox, rzBox);
//Creating a Group object
Group root = new Group(box);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing a cylinder");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac RotationExample3D.java
java RotationExample3D
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
JavaFX - Animations
通常,为对象添加动画表示按照快速显示的方式创建其运动的错觉。在 JavaFX 中,可以通过在一定时间内更改节点的属性为其添加动画。JavaFX 提供了一个名为 javafx.animation 的包。此包包含用于为节点添加动画的类。Animation 是所有这些类的基类。
In general, animating an object implies creating illusion of its motion by rapid display. In JavaFX, a node can be animated by changing its property over time. JavaFX provides a package named javafx.animation. This package contains classes that are used to animate the nodes. Animation is the base class of all these classes.
使用 JavaFX,你可应用动画(过渡),例如 Fade Transition 、 Fill Transition 、 Rotate Transition 、 Scale Transition 、 Stroke Transition 、 Translate Transition 、 Path Transition 、 Sequential Transition 、 Pause Transition 、 Parallel Transition 等。
Using JavaFX, you can apply animations (transitions) such as Fade Transition, Fill Transition, Rotate Transition, Scale Transition, Stroke Transition, Translate Transition, Path Transition, Sequential Transition, Pause Transition, Parallel Transition, etc.
所有这些过渡在包 javafx.animation 中均由单个类表示。
All these transitions are represented by individual classes in the package javafx.animation.
如需对节点应用特定动画,您必须执行以下步骤:
To apply a particular animation to a node, you have to follow the steps given below −
-
Create a require node using respective class.
-
Instantiate the respective transition (animation) class that is to be applied
-
Set the properties of the transition and
-
Finally play the transition using the play() method of the Animation class.
在本章,我们将讨论基本过渡(旋转、缩放、平移)的示例。
In this chapter we are going to discuss examples of basic transitions(Rotation, Scaling, Translation).
Rotate Transition
以下是 JavaFX 中旋转过渡演示的程序。将此代码保存在名为 RotateTransitionExample.java 的文件中。
Following is the program which demonstrates Rotate Transition in JavaFX. Save this code in a file with the name RotateTransitionExample.java.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
import javafx.util.Duration;
public class RotateTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Creating a hexagon
Polygon hexagon = new Polygon();
//Adding coordinates to the hexagon
hexagon.getPoints().addAll(new Double[]{
200.0, 50.0,
400.0, 50.0,
450.0, 150.0,
400.0, 250.0,
200.0, 250.0,
150.0, 150.0,
});
//Setting the fill color for the hexagon
hexagon.setFill(Color.BLUE);
//Creating a rotate transition
RotateTransition rotateTransition = new RotateTransition();
//Setting the duration for the transition
rotateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
rotateTransition.setNode(hexagon);
//Setting the angle of the rotation
rotateTransition.setByAngle(360);
//Setting the cycle count for the transition
rotateTransition.setCycleCount(50);
//Setting auto reverse value to false
rotateTransition.setAutoReverse(false);
//Playing the animation
rotateTransition.play();
//Creating a Group object
Group root = new Group(hexagon);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Rotate transition example ");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac RotateTransitionExample.java
java RotateTransitionExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Scale Transition
以下是展示 JavaFX 中缩放过渡的程序。将此代码保存在名为 ScaleTransitionExample.java 的文件中。
Following is the program which demonstrates Scale Transition in JavaFX. Save this code in a file with the name ScaleTransitionExample.java.
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ScaleTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(50.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Creating scale Transition
ScaleTransition scaleTransition = new ScaleTransition();
//Setting the duration for the transition
scaleTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
scaleTransition.setNode(circle);
//Setting the dimensions for scaling
scaleTransition.setByY(1.5);
scaleTransition.setByX(1.5);
//Setting the cycle count for the translation
scaleTransition.setCycleCount(50);
//Setting auto reverse value to true
scaleTransition.setAutoReverse(false);
//Playing the animation
scaleTransition.play();
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Scale transition example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac ScaleTransitionExample.java
java ScaleTransitionExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Translate Transition
以下是演示 JavaFX 中转换过渡的程序。将此代码保存在名称为 TranslateTransitionExample.java 的文件中。
Following is the program which demonstrates Translate Transition in JavaFX. Save this code in a file with the name TranslateTransitionExample.java.
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TranslateTransitionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(150.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(100.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Creating Translate Transition
TranslateTransition translateTransition = new TranslateTransition();
//Setting the duration of the transition
translateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
translateTransition.setNode(circle);
//Setting the value of the transition along the x axis.
translateTransition.setByX(300);
//Setting the cycle count for the transition
translateTransition.setCycleCount(50);
//Setting auto reverse value to false
translateTransition.setAutoReverse(false);
//Playing the animation
translateTransition.play();
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Translate transition example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac TranslateTransitionExample.java
java TranslateTransitionExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
此外,JavaFX 提供的类还可以对节点应用更多过渡。以下是 JavaFX 支持的其他类型的过渡。
In addition to these, JavaFX provides classes to apply more transitions on nodes. The following are the other kinds of transitions supported by JavaFX.
-
Transitions that effects the attributes of the nodes Fade, Fill, Stroke
-
Transition that involve more than one basic transitions Sequential, Parallel, Pause
-
Transition that translate the object along the specified path Path Transition
JavaFX - Colors
要向应用程序应用颜色,JavaFX 提供了 javafx.scene.paint 包中的各种类。该包包含一个名为 Paint 的抽象类,它是用于应用颜色的所有类的基类。
To apply colors to an application, JavaFX provides various classes in the package javafx.scene.paint package. This package contains an abstract class named Paint and it is the base class of all the classes that are used to apply colors.
使用这些类,您可以按照以下模式应用颜色 −
Using these classes, you can apply colors in the following patterns −
-
Uniform − In this pattern, color is applied uniformly throughout node.
-
Image Pattern − This lets you to fill the region of the node with an image pattern.
-
Gradient − In this pattern, the color applied to the node varies from one point to the other. It has two kinds of gradients namely Linear Gradient and Radial Gradient.
您可以向其应用颜色的所有那些节点类,例如 Shape, Text (包括场景),都具有名为 setFill() 和 setStroke() 的方法。这些将分别有助于设置节点的颜色值及其笔触。
All those node classes to which you can apply color such as Shape, Text (including Scene), have methods named setFill() and setStroke(). These will help to set the color values of the nodes and their strokes respectively.
这些方法接受 Paint 类型的对象。因此,要创建这些类型的图像之一,您需要实例化这些类并将对象作为参数传递给这些方法。
These methods accept an object of type Paint. Therefore, to create either of these type of images, you need to instantiate these classes and pass the object as a parameter to these methods.
Applying Color to the Nodes
要向节点设置统一的颜色模式,您需要将 color 类的静态变量传递给 setFill() 、 setStroke() 方法,如下所示 −
To set uniform color pattern to the nodes, you need to pass an object of the class color to the setFill(), setStroke() methods as follows −
//Setting color to the text
Color color = new Color.BEIGE
text.setFill(color);
//Setting color to the stroke
Color color = new Color.DARKSLATEBLUE
circle.setStroke(color);
在上述代码块中,我们使用 color 类 的静态变量来创建一个颜色对象。
In the above code block, we are using the static variables of the color class to create a color object.
同样,您还可以使用 RGB 值或 HSB 标准的着色或颜色网页哈希代码,如下所示 −
In the same way, you can also use the RGB values or HSB standard of coloring or web hash codes of colors as shown below −
//creating color object by passing RGB values
Color c = Color.rgb(0,0,255);
//creating color object by passing HSB values
Color c = Color.hsb(270,1.0,1.0);
//creating color object by passing the hash code for web
Color c = Color.web("0x0000FF",1.0);
Example
下面是一个示例,演示如何将颜色应用于 JavaFX 中的节点。这里,我们正在创建圆形和文本节点,并向其应用颜色。
Following is an example which demonstrates, how to apply color to the nodes in JavaFX. Here, we are creating a circle and text nodes and applying colors to them.
将此代码保存在名为 ColorExample.java 的文件中。
Save this code in a file with the name ColorExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class ColorExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(180.0f);
circle.setRadius(90.0f);
//Setting color to the circle
circle.setFill(Color.DARKRED);
//Setting the stroke width
circle.setStrokeWidth(3);
//Setting color to the stroke
circle.setStroke(Color.DARKSLATEBLUE);
//Drawing a text
Text text = new Text("This is a colored circle");
//Setting the font of the text
text.setFont(Font.font("Edwardian Script ITC", 50));
//Setting the position of the text
text.setX(155);
text.setY(50);
//Setting color to the text
text.setFill(Color.BEIGE);
text.setStrokeWidth(2);
text.setStroke(Color.DARKSLATEBLUE);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Color Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac ColorExample.java
java ColorExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
Applying Image Pattern to the Nodes
要对节点应用图像模式,请实例化 ImagePattern 类,并将它的对象传递给 setFill() 、 setStroke() 方法。
To apply an image pattern to the nodes, instantiate the ImagePattern class and pass its object to the setFill(), setStroke() methods.
该类的构造函数接受六个参数,即 −
The constructor of this class accepts six parameters namely −
-
Image − The object of the image using which you want to create the pattern.
-
x and y − Double variables representing the (x, y) coordinates of origin of the anchor rectangle.
-
height and width − Double variables representing the height and width of the image that is used to create a pattern.
-
isProportional − This is a Boolean Variable; on setting this property to true, the start and end locations are set to be proportional.
ImagePattern radialGradient = new ImagePattern(dots, 20, 20, 40, 40, false);
Example
下面是一个示例,演示如何将图像模式应用于 JavaFX 中的节点。这里,我们正在创建圆形和文本节点,并向其应用图像模式。
Following is an example which demonstrates how to apply image pattern to the nodes in JavaFX. Here, we are creating a circle and a text node and applying an image pattern to them.
将此代码保存在名为 ImagePatternExample.java 的文件中。
Save this code in a file with name ImagePatternExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class ImagePatternExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(180.0f);
circle.setRadius(90.0f);
//Drawing a text
Text text = new Text("This is a colored circle");
//Setting the font of the text
text.setFont(Font.font("Edwardian Script ITC", 50));
//Setting the position of the text
text.setX(155);
text.setY(50);
//Setting the image pattern
String link = "https://encrypted-tbn1.gstatic.com"
+ "/images?q=tbn:ANd9GcRQub4GvEezKMsiIf67U"
+ "rOxSzQuQ9zl5ysnjRn87VOC8tAdgmAJjcwZ2qM";
Image image = new Image(link);
ImagePattern radialGradient = new ImagePattern(image, 20, 20, 40, 40, false);
//Setting the linear gradient to the circle and text
circle.setFill(radialGradient);
text.setFill(radialGradient);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Image pattern Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac ImagePatternExample.java
java ImagePatternExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
Applying Linear Gradient Pattern
要在节点上应用线性渐变模式,实例化 LinearGradient 类并将其对象传递给 setFill(), setStroke() 方法。
To apply a Linear Gradient Pattern to the nodes, instantiate the LinearGradient class and pass its object to the setFill(), setStroke() methods.
此类的构造函数接受五个参数,即:
The constructor of this class accepts five parameters namely −
-
startX, startY − These double properties represent the x and y coordinates of the starting point of the gradient.
-
endX, endY − These double properties represent the x and y coordinates of the ending point of the gradient.
-
cycleMethod − This argument defines how the regions outside the color gradient bounds, defined by the starting and ending points, should be filled.
-
proportional − This is a Boolean Variable; on setting this property to true, the start and end locations are set to a proportion.
-
Stops − This argument defines the color-stop points along the gradient line.
//Setting the linear gradient
Stop[] stops = new Stop[] {
new Stop(0, Color.DARKSLATEBLUE),
new Stop(1, Color.DARKRED)
};
LinearGradient linearGradient =
new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
Example
以下是一个示例,演示如何在 JavaFX 中的节点上应用渐变模式。在此,我们创建一个圆形和一个文本节点,并向其应用线性渐变模式。
Following is an example which demonstrates how to apply a gradient pattern to the nodes in JavaFX. Here, we are creating a circle and a text nodes and applying linear gradient pattern to them.
将此代码保存在名为 LinearGradientExample.java 的文件中。
Save this code in a file with name LinearGradientExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class LinearGradientExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(180.0f);
circle.setRadius(90.0f);
//Drawing a text
Text text = new Text("This is a colored circle");
//Setting the font of the text
text.setFont(Font.font("Edwardian Script ITC", 55));
//Setting the position of the text
text.setX(140);
text.setY(50);
//Setting the linear gradient
Stop[] stops = new Stop[] {
new Stop(0, Color.DARKSLATEBLUE),
new Stop(1, Color.DARKRED)
};
LinearGradient linearGradient =
new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
//Setting the linear gradient to the circle and text
circle.setFill(linearGradient);
text.setFill(linearGradient);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Linear Gradient Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac LinearGradientExample.java
java LinearGradientExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
Applying Radial Gradient Pattern
要将径向渐变模式应用于节点,请实例化 GradientPattern 类并将其对象传递给 setFill(), setStroke() 方法。
To apply a Radial Gradient Pattern to the nodes, instantiate the GradientPattern class and pass its object to the setFill(), setStroke() methods.
此类的构造函数接受一些参数,其中一些是:
The constructor of this class accepts a few parameters, some of which are −
-
startX, startY − These double properties represent the x and y coordinates of the starting point of the gradient.
-
endX, endY − These double properties represent the x and y coordinates of the ending point of the gradient.
-
cycleMethod − This argument defines how the regions outside the color gradient bounds are defined by the starting and ending points and how they should be filled.
-
proportional − This is a Boolean Variable; on setting this property to true the start and end locations are set to a proportion.
-
Stops − This argument defines the color-stop points along the gradient line.
//Setting the radial gradient
Stop[] stops = new Stop[] {
new Stop(0.0, Color.WHITE),
new Stop(0.3, Color.RED),
new Stop(1.0, Color.DARKRED)
};
RadialGradient radialGradient =
new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops);
Example
以下是一个示例,演示如何在 JavaFX 中将径向渐变模式应用于节点。在此处,我们创建一个圆形和一个文本节点,并将渐变模式应用于它们。
Following is an example which demonstrates how to apply a radial gradient pattern to the nodes in JavaFX. Here, we are creating a circle and a text nodes and applying gradient pattern to them.
将此代码保存在文件 RadialGradientExample.java 中。
Save this code in a file with the name RadialGradientExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class RadialGradientExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(180.0f);
circle.setRadius(90.0f);
//Drawing a text
Text text = new Text("This is a colored circle");
//Setting the font of the text
text.setFont(Font.font("Edwardian Script ITC", 50));
//Setting the position of the text
text.setX(155);
text.setY(50);
//Setting the radial gradient
Stop[] stops = new Stop[] {
new Stop(0.0, Color.WHITE),
new Stop(0.3, Color.RED),
new Stop(1.0, Color.DARKRED)
};
RadialGradient radialGradient =
new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops);
//Setting the radial gradient to the circle and text
circle.setFill(radialGradient);
text.setFill(radialGradient);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Radial Gradient Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac RadialGradientExample.java
java RadialGradientExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
JavaFX - Images
可以使用 JavaFX 在包 javafx.scene.image 提供的类加载和修改图像。JavaFX 支持以下图像格式 Bmp, Gif, Jpeg, Png 。
You can load and modify images using the classes provided by JavaFX in the package javafx.scene.image. JavaFX supports the image formats like Bmp, Gif, Jpeg, Png.
本章将说明如何在 JavaFX 中加载图像、如何在多个视图中投影图像以及如何修改图像的像素。
This chapter teaches you how to load images in to JavaFX, how to project an image in multiple views and how to alter the pixels of an image.
Loading an Image
你可以通过实例化 javafx.scene.image 包中的名为 Image 的类,在 JavaFX 中加载图像。
You can load an image in JavaFX by instantiating the class named Image of the package javafx.scene.image.
必须将以下任一项传递给该类的构造函数 −
To the constructor of the class, you have to pass either of the following −
-
An InputStream object of the image to be loaded or,
-
A string variable holding the URL for the image.
//Passing FileInputStream object as a parameter
FileInputStream inputstream = new FileInputStream("C:\\images\\image.jpg");
Image image = new Image(inputstream);
//Loading image from URL
//Image image = new Image(new FileInputStream("url for the image));
加载图像之后,您可以通过实例化 ImageView 类并将图像传递给其构造函数来设置图像视图,如下所示 −
After loading the image, you can set the view for the image by instantiating the ImageView class and passing the image to its constructor as follows −
ImageView imageView = new ImageView(image);
Example
以下示例演示了如何在 JavaFX 中加载图像并设置视图。
Following is an example which demonstrates how to load an image in JavaFX and set the view.
将此代码另存为名为 ImageExample.java 的文件。
Save this code in a file with the name ImageExample.java.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class ImageExample extends Application {
@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("path of the image"));
//Setting the image view
ImageView imageView = new ImageView(image);
//Setting the position of the image
imageView.setX(50);
imageView.setY(25);
//setting the fit height and width of the image view
imageView.setFitHeight(455);
imageView.setFitWidth(500);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
stage.setTitle("Loading an image");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac ImageExample.java
java ImageExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
Multiple Views of an Image
你还可以为同一场景中的图像设置多个视图。以下程序是一个示例,它演示了如何在 JavaFX 中为场景中的图像设置各种视图。
You can also set multiple views for an image in the same scene. The following program is an example that demonstrates how to set various views for an image in a scene in JavaFX.
将此代码另存为名为 MultipleViews.java 的文件。
Save this code in a file with the name MultipleViews.java.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class MultipleViews extends Application {
@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("file path"));
//Setting the image view 1
ImageView imageView1 = new ImageView(image);
//Setting the position of the image
imageView1.setX(50);
imageView1.setY(25);
//setting the fit height and width of the image view
imageView1.setFitHeight(300);
imageView1.setFitWidth(250);
//Setting the preserve ratio of the image view
imageView1.setPreserveRatio(true);
//Setting the image view 2
ImageView imageView2 = new ImageView(image);
//Setting the position of the image
imageView2.setX(350);
imageView2.setY(25);
//setting the fit height and width of the image view
imageView2.setFitHeight(150);
imageView2.setFitWidth(250);
//Setting the preserve ratio of the image view
imageView2.setPreserveRatio(true);
//Setting the image view 3
ImageView imageView3 = new ImageView(image);
//Setting the position of the image
imageView3.setX(350);
imageView3.setY(200);
//setting the fit height and width of the image view
imageView3.setFitHeight(100);
imageView3.setFitWidth(100);
//Setting the preserve ratio of the image view
imageView3.setPreserveRatio(true);
//Creating a Group object
Group root = new Group(imageView1, imageView2, imageView3);
//Creating a scene object
Scene scene = new Scene(root, 600, 400);
//Setting title to the Stage
stage.setTitle("Multiple views of an image");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac MultipleViews.java
java MultipleViews
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
Writing Pixels
JavaFX 提供名为 PixelReader 和 PixelWriter 的类来读取和写入图像的像素。 WritableImage 类用于创建一个可写图像。
JavaFX provides classes named PixelReader and PixelWriter classes to read and write pixels of an image. The WritableImage class is used to create a writable image.
以下是演示如何读写图像像素的示例。在这里,我们读入图像的颜色值,并使其变暗。
Following is an example which demonstrates how to read and write pixels of an image. Here, we are reading the color value of an image and making it darker.
将此代码另存为名为 WritingPixelsExample.java 的文件。
Save this code in a file with the name WritingPixelsExample.java.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class WritingPixelsExample extends Application {
@Override
public void start(Stage stage) throws FileNotFoundException {
//Creating an image
Image image = new Image(new FileInputStream("C:\\images\\logo.jpg"));
int width = (int)image.getWidth();
int height = (int)image.getHeight();
//Creating a writable image
WritableImage wImage = new WritableImage(width, height);
//Reading color from the loaded image
PixelReader pixelReader = image.getPixelReader();
//getting the pixel writer
PixelWriter writer = wImage.getPixelWriter();
//Reading the color of the image
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
//Retrieving the color of the pixel of the loaded image
Color color = pixelReader.getColor(x, y);
//Setting the color to the writable image
writer.setColor(x, y, color.darker());
}
}
//Setting the view for the writable image
ImageView imageView = new ImageView(wImage);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
stage.setTitle("Writing pixels ");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac WritingPixelsExample.java
java WritingPixelsExample
执行后,以上程序将生成一个 JavaFX 窗口,如下所示 −
On executing, the above program generates a JavaFX window as follows −
JavaFX - 3D Shapes
在前面的章节中,我们已经了解了如何在线段图上绘画二维形状。除了这些二维形状,我们还可以使用 JavaFX 绘画一些其他三维形状。
In the earlier chapters, we have seen how to draw 2D shapes on an XY plane. In addition to these 2D shapes, we can draw several other 3D shapes as well using JavaFX.
3D Shape
通常,三维形状是可以绘制在线段图上的几何图形。其中包括一个 Cylinder, Sphere 和一个 Box 。
In general, a 3D shape is a geometrical figure that can be drawn on the XYZ plane. These include a Cylinder, Sphere and a Box.
以上提到的每个 3D 形状都由一个类表示,且所有这些类都属于包 javafx.scene.shape 。名为 Shape3D 的类是 JavaFX 中所有 3D 形状的基类。
Each of the above mentioned 3D shape is represented by a class and all these classes belong to the package javafx.scene.shape. The class named Shape3D is the base class of all the 3-Dimensional shapes in JavaFX.
Creating a 3D Shape
要创建一个 3D 形状,你需要:
To create a 3-Dimensional shape, you need to −
-
Instantiate the respective class of the required 3D shape.
-
Set the properties of the 3D shape.
-
Add the 3D shape object to the group.
Instantiating the Respective Class
要创建一个 3D 形状,首先需要实例化其相应类。例如,如果要创建一个 3D 盒子,你需要实例化名为 Box 的类,如下所示:
To create a 3-Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a 3D box, you need to instantiate the class named Box as follows −
Box box = new Box();
Setting the Properties of the Shape
实例化该类后,你需要使用 setter 方法为该形状设置属性。
After instantiating the class, you need to set the properties for the shape using the setter methods.
例如,要绘制一个 3D 盒子,你需要传递其宽度、高度和深度。你可以使用其各自的 setter 方法指定这些值,如下所示:
For example, to draw a 3D box you need to pass its Width, Height, Depth. You can specify these values using their respective setter methods as follows −
//Setting the properties of the Box
box.setWidth(200.0);
box.setHeight(400.0);
box.setDepth(200.0);
Adding the Shape Object to the Group
最后,你需要将形状的对象添加到组中,方法是将其作为构造函数的参数进行传递,如下所示。
Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below.
//Creating a Group object
Group root = new Group(box);
下表提供了 JavaFX 提供的各种 3D 形状的列表。
The following table gives you the list of various 3D shapes provided by JavaFX.
S.No |
Shape & Description |
1 |
BoxA cuboid is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a three-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Box node in JavaFX. This class has 3 properties of the double datatype namely − width − The width of the box. height − The height of the box. depth − The depth of the box. |
2 |
CylinderA cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface. It is described by two parameters, namely, the radius of its circular base and the height of the cylinder. In JavaFX, a cylinder is represented by a class named Cylinder. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a cylinder node in JavaFX. This class has 2 properties of the double datatype namely − height − The height of the Cylinder. radius − The radius of the Cylinder. |
3 |
SphereA sphere is defined as the set of points that are all at the same distance r from a given point in a 3D space. This distance r is the radius of the sphere and the given point is the centre of the sphere. In JavaFX, a sphere is represented by a class named Sphere. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a sphere node in JavaFX. This class has a property named radius of double datatype. It represents the radius of a Sphere. |
Properties of 3D Objects
对于所有 3 维对象,可以设置各种属性,如剔除面、绘制模式、材质。
For all the 3 Dimensional objects, you can set various properties like Cull Face, Drawing Mode, Material.
以下部分讨论 3D 对象的属性。
The following section discusses the properties of 3D objects.
Cull Face
通常,剔除是指移除形状中方向不当的部分(在视图区域中不可见)。
In general, culling is the removal of improperly oriented parts of a shape (which are not visible in the view area).
剔除面属性的类型为 CullFace ,它表示 3D 形状的剔除面。你可以使用 setCullFace() 方法设置形状的剔除面,如下所示:
The Cull Face property is of the type CullFace and it represents the Cull Face of a 3D shape. You can set the Cull Face of a shape using the method setCullFace() as shown below −
box.setCullFace(CullFace.NONE);
形状的描边类型可以是:
The stroke type of a shape can be −
-
None − No culling is performed (CullFace.NONE).
-
Front − All the front facing polygons are culled. (CullFace.FRONT).
-
Back − All the back facing polygons are culled. (StrokeType.BACK).
默认情况下,三维图形的剔除面是反面。
By default, the cull face of a 3-Dimensional shape is Back.
Example
以下程序演示了球体的各种剔除面的示例。将此代码保存在名为 SphereCullFace.java 的文件中。
The following program is an example which demonstrates various cull faces of the sphere. Save this code in a file with the name SphereCullFace.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.CullFace;
import javafx.stage.Stage;
import javafx.scene.shape.Sphere;
public class SphereCullFace extends Application {
@Override
public void start(Stage stage) {
//Drawing Sphere1
Sphere sphere1 = new Sphere();
//Setting the radius of the Sphere
sphere1.setRadius(50.0);
//Setting the position of the sphere
sphere1.setTranslateX(100);
sphere1.setTranslateY(150);
//setting the cull face of the sphere to front
sphere1.setCullFace(CullFace.FRONT);
//Drawing Sphere2
Sphere sphere2 = new Sphere();
//Setting the radius of the Sphere
sphere2.setRadius(50.0);
//Setting the position of the sphere
sphere2.setTranslateX(300);
sphere2.setTranslateY(150);
//Setting the cull face of the sphere to back
sphere2.setCullFace(CullFace.BACK);
//Drawing Sphere3
Sphere sphere3 = new Sphere();
//Setting the radius of the Sphere
sphere3.setRadius(50.0);
//Setting the position of the sphere
sphere3.setTranslateX(500);
sphere3.setTranslateY(150);
//Setting the cull face of the sphere to none
sphere2.setCullFace(CullFace.NONE);
//Creating a Group object
Group root = new Group(sphere1, sphere2, sphere3);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing a Sphere");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令从命令提示符处编译并执行已保存的 Java 文件。
Compile and execute the saved Java file from the command prompt using the following commands.
javac SphereCullFace.java
java SphereCullFace
在执行时,上述程序将生成一个 JavaFX 窗口,其中显示了三个球体,它们的面剔除值分别为 FRONT, BACK 和 NONE ,如下所示:
On executing, the above program generates a JavaFX window displaying three spheres with cull face values FRONT, BACK and NONE respectively as follows −
Drawing Modes
此属性的类型为 DrawMode ,它表示用于绘制当前 3D 形状的绘制模式。可以使用 setDrawMode() 方法选择用于绘制 3D 形状的绘制模式,如下所示:
It is the property is of the type DrawMode and it represents the drawing mode used to draw the current 3D shape. You can choose the draw mode to draw a 3D shape using the method setDrawMode () as follows −
box.setDrawMode(DrawMode.FILL);
在 JavaFX 中,可以选择两种绘制模式来绘制 3D 形状,即:-
In JavaFX, you can choose two draw modes to draw a 3D shape, which are −
-
Fill − This mode draws and fills a 2D shape (DrawMode.FILL).
-
Line − This mode draws a 3D shape using lines (DrawMode.LINE).
默认情况下,3D 形状的绘制模式为填充。
By default, the drawing mode of a 3Dimensional shape is fill.
Example
以下程序是一个例子,它演示了 3D 盒子的各种绘制模式。将此代码保存在一个名为 BoxDrawMode.java 的文件中。
The following program is an example which demonstrates various draw modes of a 3D box. Save this code in a file with the name BoxDrawMode.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.shape.Box;
import javafx.scene.shape.DrawMode;
import javafx.stage.Stage;
public class BoxDrawMode extends Application {
@Override
public void start(Stage stage) {
//Drawing a Box
Box box1 = new Box();
//Setting the properties of the Box
box1.setWidth(100.0);
box1.setHeight(100.0);
box1.setDepth(100.0);
//Setting the position of the box
box1.setTranslateX(200);
box1.setTranslateY(150);
box1.setTranslateZ(0);
//Setting the drawing mode of the box
box1.setDrawMode(DrawMode.LINE);
//Drawing a Box
Box box2 = new Box();
//Setting the properties of the Box
box2.setWidth(100.0);
box2.setHeight(100.0);
box2.setDepth(100.0);
//Setting the position of the box
box2.setTranslateX(450); //450
box2.setTranslateY(150);//150
box2.setTranslateZ(300);
//Setting the drawing mode of the box
box2.setDrawMode(DrawMode.FILL);
//Creating a Group object
Group root = new Group(box1, box2);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
//Setting title to the Stage
stage.setTitle("Drawing a Box");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac BoxDrawMode.java
java BoxDrawMode
在执行时,上述程序将生成一个 JavaFX 窗口,其中显示了两个盒子,它们的绘制模式值分别为 LINE 和 FILL,如下所示:
On executing, the above program generates a JavaFX window displaying two boxes with draw mode values LINE and FILL respectively, as follows −
Material
面剔除属性的类型为 Material ,它用于选择 3D 形状的材质表面。可以使用 setCullFace() 方法设置 3D 形状的材质,如下所示:
The cull Face property is of the type Material and it is used to choose the surface of the material of a 3D shape. You can set the material of a 3D shape using the method setCullFace() as follows −
cylinder.setMaterial(material);
如上述此方法所述,您需要传递类型为材料的对象。包 javafx.scene.paint 的 PhongMaterial 类是此类的子类,并提供 7 个表示 Phong 着色材质的属性。您可以使用这些属性的 setter 方法将所有这些类型的材质应用于 3D 形状的表面。
As mentioned above for this method, you need to pass an object of the type Material. The PhongMaterial class of the package javafx.scene.paint is a sub class of this class and provides 7 properties that represent a Phong shaded material. You can apply all these type of materials to the surface of a 3D shape using the setter methods of these properties.
以下是 JavaFX 中提供的材质类型 −
Following are the type of materials that are available in JavaFX −
-
bumpMap − This represents a normal map stored as a RGB Image.
-
diffuseMap − This represents a diffuse map.
-
selfIlluminationMap − This represents a self-illumination map of this PhongMaterial.
-
specularMap − This represents a specular map of this PhongMaterial.
-
diffuseColor − This represents a diffuse color of this PhongMaterial.
-
specularColor − This represents a specular color of this PhongMaterial.
-
specularPower − This represents a specular power of this PhongMaterial.
默认情况下,3D 形状的材质是漫射颜色为浅灰色的 PhongMaterial。
By default, the material of a 3-Dimensional shape is a PhongMaterial with a diffuse color of light gray.
Example
以下是一个示例,它显示圆柱上各种材质。将此代码保存在名为 CylinderMaterials.java 的文件中。
Following is an example which displays various materials on the cylinder. Save this code in a file with the name CylinderMaterials.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Cylinder;
import javafx.stage.Stage;
public class CylinderMaterials extends Application {
@Override
public void start(Stage stage) {
//Drawing Cylinder1
Cylinder cylinder1 = new Cylinder();
//Setting the properties of the Cylinder
cylinder1.setHeight(130.0f);
cylinder1.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder1.setTranslateX(100);
cylinder1.setTranslateY(75);
//Preparing the phong material of type bump map
PhongMaterial material1 = new PhongMaterial();
material1.setBumpMap(new Image
("http://www.tutorialspoint.com/images/tplogo.gif"));
//Setting the bump map material to Cylinder1
cylinder1.setMaterial(material1);
//Drawing Cylinder2
Cylinder cylinder2 = new Cylinder();
//Setting the properties of the Cylinder
cylinder2.setHeight(130.0f);
cylinder2.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder2.setTranslateX(200);
cylinder2.setTranslateY(75);
//Preparing the phong material of type diffuse map
PhongMaterial material2 = new PhongMaterial();
material2.setDiffuseMap(new Image
("http://www.tutorialspoint.com/images/tp-logo.gif"));
//Setting the diffuse map material to Cylinder2
cylinder2.setMaterial(material2);
//Drawing Cylinder3
Cylinder cylinder3 = new Cylinder();
//Setting the properties of the Cylinder
cylinder3.setHeight(130.0f);
cylinder3.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder3.setTranslateX(300);
cylinder3.setTranslateY(75);
//Preparing the phong material of type Self Illumination Map
PhongMaterial material3 = new PhongMaterial();
material3.setSelfIlluminationMap(new Image
("http://www.tutorialspoint.com/images/tp-logo.gif"));
//Setting the Self Illumination Map material to Cylinder3
cylinder3.setMaterial(material3);
//Drawing Cylinder4
Cylinder cylinder4 = new Cylinder();
//Setting the properties of the Cylinder
cylinder4.setHeight(130.0f);
cylinder4.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder4.setTranslateX(400);
cylinder4.setTranslateY(75);
//Preparing the phong material of type Specular Map
PhongMaterial material4 = new PhongMaterial();
material4.setSpecularMap(new Image
("http://www.tutorialspoint.com/images/tp-logo.gif"));
//Setting the Specular Map material to Cylinder4
cylinder4.setMaterial(material4);
//Drawing Cylinder5
Cylinder cylinder5 = new Cylinder();
//Setting the properties of the Cylinder
cylinder5.setHeight(130.0f);
cylinder5.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder5.setTranslateX(100);
cylinder5.setTranslateY(300);
//Preparing the phong material of type diffuse color
PhongMaterial material5 = new PhongMaterial();
material5.setDiffuseColor(Color.BLANCHEDALMOND);
//Setting the diffuse color material to Cylinder5
cylinder5.setMaterial(material5);
//Drawing Cylinder6
Cylinder cylinder6 = new Cylinder();
//Setting the properties of the Cylinder
cylinder6.setHeight(130.0f);
cylinder6.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder6.setTranslateX(200);
cylinder6.setTranslateY(300);
//Preparing the phong material of type specular color
PhongMaterial material6 = new PhongMaterial();
//setting the specular color map to the material
material6.setSpecularColor(Color.BLANCHEDALMOND);
//Setting the specular color material to Cylinder6
cylinder6.setMaterial(material6);
//Drawing Cylinder7
Cylinder cylinder7 = new Cylinder();
//Setting the properties of the Cylinder
cylinder7.setHeight(130.0f);
cylinder7.setRadius(30.0f);
//Setting the position of the Cylinder
cylinder7.setTranslateX(300);
cylinder7.setTranslateY(300);
//Preparing the phong material of type Specular Power
PhongMaterial material7 = new PhongMaterial();
material7.setSpecularPower(0.1);
//Setting the Specular Power material to the Cylinder
cylinder7.setMaterial(material7);
//Creating a Group object
Group root = new Group(cylinder1 ,cylinder2, cylinder3,
cylinder4, cylinder5, cylinder6, cylinder7);
//Creating a scene object
Scene scene = new Scene(root, 600, 400);
//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(-10);
scene.setCamera(camera);
//Setting title to the Stage
stage.setTitle("Drawing a cylinder");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
Javac CylinderMaterials.java
java CylinderMaterials
在执行时,上述程序将生成一个 JavaFX 窗口,其中显示 7 个带有材质、凹凸贴图、漫反射贴图、自发光贴图、镜面贴图、漫反射颜色、镜面颜色、(杏仁白)镜面强度,分别如以下屏幕截图所示 −
On executing, the above program generates a JavaFX window displaying 7 cylinders with Materials, Bump Map, Diffuse Map, Self-Illumination Map, Specular Map, Diffuse Color, Specular Color, (BLANCHEDALMOND) Specular Power, respectively, as shown in the following screenshot −
JavaFX - Event Handling
在 JavaFX 中,我们可以开发 GUI 应用程序、Web 应用程序和图形应用程序。在这样的应用程序中,用户与应用程序(节点)交互时,就会说有一个事件已经发生。
In JavaFX, we can develop GUI applications, web applications and graphical applications. In such applications, whenever a user interacts with the application (nodes), an event is said to have been occurred.
例如,单击按钮、移动鼠标、通过键盘输入字符、从列表中选择项目、滚动页面都是导致事件发生的活动。
For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Events
事件可以大致分为以下两类 −
The events can be broadly classified into the following two categories −
-
Foreground Events − Those events which require the direct interaction of a user. They are generated as consequences of a person interacting with the graphical components in a Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
-
Background Events − Those events that don’t require the interaction of end-user are known as background events. The operating system interruptions, hardware or software failure, timer expiry, operation completion are the example of background events.
Events in JavaFX
JavaFX 提供支持以处理各种事件。名为 Event 的包中的类是事件的基本类。
JavaFX provides support to handle a wide varieties of events. The class named Event of the package javafx.event is the base class for an event.
任何其子类的实例都是一个事件。JavaFX 提供了各种各样的事件。其中一些如下所示。
An instance of any of its subclass is an event. JavaFX provides a wide variety of events. Some of them are are listed below.
-
Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited target, etc.
-
Key Event − This is an input event that indicates the key stroke occurred on a node. It is represented by the class named KeyEvent. This event includes actions like key pressed, key released and key typed.
-
Drag Event − This is an input event which occurs when the mouse is dragged. It is represented by the class named DragEvent. It includes actions like drag entered, drag dropped, drag entered target, drag exited target, drag over, etc.
-
Window Event − This is an event related to window showing/hiding actions. It is represented by the class named WindowEvent. It includes actions like window hiding, window shown, window hidden, window showing, etc.
Event Handling
事件处理是控制事件的机制,并决定如果事件发生,该发生什么。此机制具有称为事件处理程序的代码,当事件发生时执行该代码。
Event Handling is the mechanism that controls the event and decides what should happen, if an event occurs. This mechanism has the code which is known as an event handler that is executed when an event occurs.
JavaFX 提供处理程序和过滤器来处理事件。在 JavaFX 中,每个事件都有 −
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
-
Target − The node on which an event occurred. A target can be a window, scene, and a node.
-
Source − The source from which the event is generated will be the source of the event. In the above scenario, mouse is the source of the event.
-
Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse released are the type of events.
假设我们有一个应用程序,其中插入了一个圆形、停止和播放按钮,如下所示,使用了一个组对象 −
Assume that we have an application which has a Circle, Stop and Play Buttons inserted using a group object as follows −
如果单击播放按钮,源将是鼠标,目标节点将是播放按钮,并且生成的事件的类型是鼠标点击。
If you click on the play button, the source will be the mouse, the target node will be the play button and the type of the event generated is the mouse click.
Phases of Event Handling in JavaFX
每当产生事件时,JavaFX 会经历以下阶段。
Whenever an event is generated, JavaFX undergoes the following phases.
Route Construction
每次生成一个事件时,事件的默认/初始路由由 Event Dispatch chain 的构建来确定。它从舞台到源节点的一条路径。
Whenever an event is generated, the default/initial route of the event is determined by construction of an Event Dispatch chain. It is the path from the stage to the source Node.
在上面的场景中,当我们点击播放按钮时,以下是为所生成的事件分发的事件分发链。
Following is the event dispatch chain for the event generated, when we click on the play button in the above scenario.
Event Capturing Phase
在构建事件分发链之后,应用程序的根节点分发该事件。此事件会传递到分发链中的所有节点(从上到下)。如果其中任何一个节点具有为所生成事件注册的 filter ,它将被执行。如果分发链中的任何节点都没有针对所生成事件的过滤器,则它将被传递到目标节点,最后目标节点将处理该事件。
After the construction of the event dispatch chain, the root node of the application dispatches the event. This event travels to all nodes in the dispatch chain (from top to bottom). If any of these nodes has a filter registered for the generated event, it will be executed. If none of the nodes in the dispatch chain has a filter for the event generated, then it is passed to the target node and finally the target node processes the event.
Event Bubbling Phase
在事件冒泡阶段,事件从目标节点到舞台节点(从下到上)传递。如果事件分发链中的任何一个节点具有为所生成事件注册的 handler ,它将被执行。如果所有这些节点都没有处理器来处理事件,则事件将到达根节点,最终进程将完成。
In the event bubbling phase, the event is travelled from the target node to the stage node (bottom to top). If any of the nodes in the event dispatch chain has a handler registered for the generated event, it will be executed. If none of these nodes have handlers to handle the event, then the event reaches the root node and finally the process will be completed.
Event Handlers and Filters
事件过滤器和处理器包含用于处理事件的应用程序逻辑。一个节点可以注册到多个处理器/过滤器。对于父子节点,您可以为父节点提供一个公共过滤器/处理器,此过滤器/处理器作为所有子节点的默认值进行处理。
Event filters and handlers are those which contains application logic to process an event. A node can register to more than one handler/filter. In case of parent–child nodes, you can provide a common filter/handler to the parents, which is processed as default for all the child nodes.
如上文所述,在事件处理期间,过滤器将被执行,在事件冒泡阶段,处理器将被执行。所有处理器和过滤器都实现包 javafx.event 的接口 EventHandler 。
As mentioned above, during the event, processing is a filter that is executed and during the event bubbling phase, a handler is executed. All the handlers and filters implement the interface EventHandler of the package javafx.event.
Adding and Removing Event Filter
要向节点添加事件过滤器,你需要使用 Node 类的 addEventFilter() 方法注册此过滤器。
To add an event filter to a node, you need to register this filter using the method addEventFilter() of the Node class.
//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding event Filter
Circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
通过如下所示的方式,你可以用 removeEventFilter() 方法删除过滤器:
In the same way, you can remove a filter using the method removeEventFilter() as shown below −
circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
Event Handling Example
以下是演示了如何在 JavaFX 中使用事件筛选器处理事件的一个示例。将此代码保存在名为 EventFiltersExample.java 的文件中。
Following is an example demonstrating the event handling in JavaFX using the event filters. Save this code in a file with name EventFiltersExample.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
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.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class EventFiltersExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(25.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Setting the text
Text text = new Text("Click on the circle to change its color");
//Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));
//Setting the color of the text
text.setFill(Color.CRIMSON);
//setting the position of the text
text.setX(150);
text.setY(50);
//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Registering the event filter
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting the fill color to the scene
scene.setFill(Color.LAVENDER);
//Setting title to the Stage
stage.setTitle("Event Filters Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac EventFiltersExample.java
java EventFiltersExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Adding and Removing Event Handlers
若要向节点添加事件处理程序,你需要使用 Node 类的 addEventHandler() 方法注册此处理程序,如下所示:
To add an event handler to a node, you need to register this handler using the method addEventHandler() of the Node class as shown below.
//Creating the mouse event handler
EventHandler<javafx.scene.input.MouseEvent> eventHandler =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding the event handler
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);
同样,你可以使用 removeEventHandler() 方法删除事件处理程序,如下所示:
In the same way, you can remove an event handler using the method removeEventHandler() as shown below −
circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
Example
以下程序演示了如何在 JavaFX 中使用事件处理程序进行事件处理的示例。
The following program is an example demonstrating the event handling in JavaFX using the event handlers.
使用 EventHandlersExample.java 名称将此代码保存在文件中。
Save this code in a file with name EventHandlersExample.java.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
public class EventHandlersExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();
//Setting the properties of the Box
box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(100.0);
//Setting the position of the box
box.setTranslateX(350);
box.setTranslateY(150);
box.setTranslateZ(50);
//Setting the text
Text text = new Text("Type any letter to rotate the box,
and click on the box to stop the rotation");
//Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));
//Setting the color of the text
text.setFill(Color.CRIMSON);
//setting the position of the text
text.setX(20);
text.setY(50);
//Setting the material of the box
PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.DARKSLATEBLUE);
//Setting the diffuse color material to box
box.setMaterial(material);
//Setting the rotation animation to the box
RotateTransition rotateTransition = new RotateTransition();
//Setting the duration for the transition
rotateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
rotateTransition.setNode(box);
//Setting the axis of the rotation
rotateTransition.setAxis(Rotate.Y_AXIS);
//Setting the angle of the rotation
rotateTransition.setByAngle(360);
//Setting the cycle count for the transition
rotateTransition.setCycleCount(50);
//Setting auto reverse value to false
rotateTransition.setAutoReverse(false);
//Creating a text filed
TextField textField = new TextField();
//Setting the position of the text field
textField.setLayoutX(50);
textField.setLayoutY(100);
//Handling the key typed event
EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
//Playing the animation
rotateTransition.play();
}
};
//Adding an event handler to the text feld
textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);
//Handling the mouse clicked event(on box)
EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
//Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);
//Creating a Group object
Group root = new Group(box, textField, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
//Setting title to the Stage
stage.setTitle("Event Handlers Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac EventHandlersExample.java
java EventHandlersExample
执行后,上述程序将生成一个 JavaFX 窗口,其中显示一个文本字段和一个 3D 框,如下所示:
On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown below −
在此,如果你在文本字段中键入一个字母,3D 框将开始沿着 x 轴旋转。如果你再次单击该框则停止旋转。
Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box again the rotation stops.
Using Convenience Methods for Event Handling
JavaFX 中的某些类定义了事件处理程序属性。通过使用各自的 setter 方法将值设置为这些属性,您可以注册到事件处理程序。这些方法称为便捷方法。
Some of the classes in JavaFX define event handler properties. By setting the values to these properties using their respective setter methods, you can register to an event handler. These methods are known as convenience methods.
这些方法大多数存在于 Node、Scene、Window 等类中,并且可用于其所有子类。
Most of these methods exist in the classes like Node, Scene, Window, etc., and they are available to all their sub classes.
例如,要像下面所示,向一个按钮中添加一个鼠标的事件监听器,你可以使用便捷的方法 setOnMouseClicked() 。
For example, to add a mouse event listener to a button, you can use the convenience method setOnMouseClicked() as shown below.
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.play();
}
}));
Example
下面的程序是一个演示在 JavaFX 中使用便捷方法进行事件处理程序的例子。
The following program is an example that demonstrates the event handling in JavaFX using the convenience methods.
将此代码保存在一个名为 ConvinienceMethodsExample.java 的文件中。
Save this code in a file with the name ConvinienceMethodsExample.java.
import javafx.animation.PathTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ConvinienceMethodsExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(25.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Creating a Path
Path path = new Path();
//Moving to the staring point
MoveTo moveTo = new MoveTo(208, 71);
//Creating 1st line
LineTo line1 = new LineTo(421, 161);
//Creating 2nd line
LineTo line2 = new LineTo(226,232);
//Creating 3rd line
LineTo line3 = new LineTo(332,52);
//Creating 4th line
LineTo line4 = new LineTo(369, 250);
//Creating 5th line
LineTo line5 = new LineTo(208, 71);
//Adding all the elements to the path
path.getElements().add(moveTo);
path.getElements().addAll(line1, line2, line3, line4, line5);
//Creating the path transition
PathTransition pathTransition = new PathTransition();
//Setting the duration of the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(circle);
//Setting the path for the transition
pathTransition.setPath(path);
//Setting the orientation of the path
pathTransition.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);
//Setting the cycle count for the transition
pathTransition.setCycleCount(50);
//Setting auto reverse value to true
pathTransition.setAutoReverse(false);
//Creating play button
Button playButton = new Button("Play");
playButton.setLayoutX(300);
playButton.setLayoutY(250);
circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
});
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.play();
}
}));
//Creating stop button
Button stopButton = new Button("stop");
stopButton.setLayoutX(250);
stopButton.setLayoutY(250);
stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.stop();
}
}));
//Creating a Group object
Group root = new Group(circle, playButton, stopButton);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
scene.setFill(Color.LAVENDER);
//Setting title to the Stage
stage.setTitle("Convenience Methods Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac ConvinienceMethodsExample.java
java ConvinienceMethodsExample
通过执行,上面的程序将产生一个 JavaFX 窗口,就像下面这样。在这里点击播放按钮以开始动画,并点击停止按钮以停止动画。
On executing, the above program generates a JavaFX window as shown below. Here click on the play button to start the animation and click on the stop button to stop the animation.
JavaFX - UI Controls
每个用户界面都考虑以下三个主要方面:
Every user interface considers the following three main aspects −
-
UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial.
-
Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.
-
Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter.
JavaFX 在软件包 javafx.scene.control 中提供了多个类。为了创建各种 GUI 组件(控件),JavaFX 支持多种控件,例如日期选取器、按钮文本字段等。
JavaFX provides several classes in the package javafx.scene.control. To create various GUI components (controls), JavaFX supports several controls such as date picker, button text field, etc.
每个控件由一个类表示;可以通过实例化其各自的类来创建控件。
Each control is represented by a class; you can create a control by instantiating its respective class.
以下是在使用 JavaFX 设计 GUI 时常用的控件列表。
Following is the list of commonly used controls while the GUI is designed using JavaFX.
S.No |
Control & Description |
1 |
Label A Label object is a component for placing text. |
2 |
Button This class creates a labeled button. |
3 |
ColorPicker A ColorPicker provides a pane of controls designed to allow a user to manipulate and select a color. |
4 |
CheckBox A CheckBox is a graphical component that can be in either an on(true) or off (false) state. |
5 |
RadioButton The RadioButton class is a graphical component, which can either be in a ON (true) or OFF (false) state in a group. |
6 |
ListView A ListView component presents the user with a scrolling list of text items. |
7 |
TextField A TextField object is a text component that allows for the editing of a single line of text. |
8 |
PasswordField A PasswordField object is a text component specialized for password entry. |
9 |
Scrollbar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values. |
10 |
FileChooser A FileChooser control represents a dialog window from which the user can select a file. |
11 |
ProgressBar As the task progresses towards completion, the progress bar displays the task’s percentage of completion. |
12 |
Slider A Slider lets the user graphically select a value by sliding a knob within a bounded interval. |
Example
以下程序是一个示例,它在 JavaFX 中显示一个登录页面。在此,我们正在使用控件 label, text field, password field 和 button 。
The following program is an example which displays a login page in JavaFX. Here, we are using the controls label, text field, password field and button.
将此代码保存在一个名为 LoginPage.java 的文件中。
Save this code in a file with the name LoginPage.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class LoginPage extends Application {
@Override
public void start(Stage stage) {
//creating label email
Text text1 = new Text("Email");
//creating label password
Text text2 = new Text("Password");
//Creating Text Filed for email
TextField textField1 = new TextField();
//Creating Text Filed for password
PasswordField textField2 = new PasswordField();
//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(400, 200);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(button1, 0, 2);
gridPane.add(button2, 1, 2);
//Styling nodes
button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
text1.setStyle("-fx-font: normal bold 20px 'serif' ");
text2.setStyle("-fx-font: normal bold 20px 'serif' ");
gridPane.setStyle("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("CSS Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac LoginPage.java
java LoginPage
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
以下程序是注册表单的示例,其演示了 JavaFX 中的控件,如 Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice List, 等。
The following program is an example of a registration form, which demonstrates controls in JavaFX such as Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice List, etc.
将此代码保存在一个名为 Registration.java 的文件中。
Save this code in a file with the name Registration.java.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
public class Registration extends Application {
@Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");
//Text field for name
TextField nameText = new TextField();
//Label for date of birth
Text dobLabel = new Text("Date of birth");
//date picker to choose date
DatePicker datePicker = new DatePicker();
//Label for gender
Text genderLabel = new Text("gender");
//Toggle group of radio buttons
ToggleGroup groupGender = new ToggleGroup();
RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);
//Label for reservation
Text reservationLabel = new Text("Reservation");
//Toggle button for reservation
ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);
//Label for technologies known
Text technologiesLabel = new Text("Technologies Known");
//check box for education
CheckBox javaCheckBox = new CheckBox("Java");
javaCheckBox.setIndeterminate(false);
//check box for education
CheckBox dotnetCheckBox = new CheckBox("DotNet");
javaCheckBox.setIndeterminate(false);
//Label for education
Text educationLabel = new Text("Educational qualification");
//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);
//Label for location
Text locationLabel = new Text("location");
//Choice box for location
ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");
//Label for register
Button buttonRegister = new Button("Register");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(500, 500);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);
gridPane.add(buttonRegister, 2, 8);
//Styling nodes
buttonRegister.setStyle(
"-fx-background-color: darkslateblue; -fx-textfill: white;");
nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
//Setting the back ground color
gridPane.setStyle("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("Registration Form");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac Registration.java
java Registration
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
JavaFX - Charts
一般而言,图表是数据的图形表示形式。有各种各样的图表来表示数据,例如 Bar Chart, Pie Chart, Line Chart, Scatter Chart, 等。
In general, a chart is a graphical representation of data. There are various kinds of charts to represent data such as Bar Chart, Pie Chart, Line Chart, Scatter Chart, etc.
JavaFX 提供对各种 Pie Charts 和 XY Charts 的支持。在 XY 平面中表示的图表包括 AreaChart, BarChart, BubbleChart, LineChart, ScatterChart, StackedAreaChart, StackedBarChart, 等。
JavaFX Provides support for various Pie Charts and XY Charts. The charts that are represented on an XY–plane include AreaChart, BarChart, BubbleChart, LineChart, ScatterChart, StackedAreaChart, StackedBarChart, etc.
每个图表都由一个类表示,所有这些图表都属于 javafx.scene.chart 包。名为 Chart 的类是 JavaFX 中所有图表的基类,而 XYChart 是在 XY 平面上绘制的所有图表的基类。
Each chart is represented by a class and all these charts belongs to the package javafx.scene.chart. The class named Chart is the base class of all the charts in JavaFX and the XYChart is base class of all those charts that are drawn on the XY–plane.
Creating a Chart
要创建图表,你需要:
To create a chart, you need to −
-
Define the axis of the chart
-
Instantiate the respective class
-
Prepare and pass data to the chart
Instantiating the Respective Class
要创建图表,请实例化其各自的类。例如,如果你要创建一条形图,你需要按如下方式实例化名为 Line 的类 −
To create a chart, instantiate its respective class. For example, if you want to create a line chart, you need to instantiate the class named Line as follows −
LineChart linechart = new LineChart(xAxis, yAxis);
如上文代码所示,在实例化时,你需要分别传递表示图表的 X 轴和 Y 轴的两个对象。
As observed in the above code, while instantiating, you need to pass two objects representing the X and Y axis of the chart respectively.
Defining the Axis
一般来说,图表轴可以表示为以下内容:
In general, the axis of the charts can be represented by −
-
Numbers such as Population, Age and
-
Categories such as Days in a Week, Countries.
在 JavaFX 中,一个轴是一个抽象类,表示 X 轴或 Y 轴。它有两个子类来定义每种类型的轴,即 CategoryAxis 和 NumberAxis ,如下图所示:
In JavaFX, an axis is an abstract class representing X or Y axis. It has two subclasses to define each type of axis, namely CategoryAxis and NumberAxis as shown in the following diagram −
Category Axis − 通过实例化此类,你可以定义(创建)X 轴或 Y 轴,每个值表示一个类别。你可以按如下所示实例化此类来定义一个类别轴 −
Category Axis − By instantiating this class, you can define (create) an X or Y axis along which each value represents a category. You can define a Category axis by instantiating this class as shown below −
CategoryAxis xAxis = new CategoryAxis();
对此轴,你需要设置类别的列表并将标签设置为如下所示:
To this axis, you need set the list of categories and label to the axis as shown below −
//setting the list of categories.
xAxis.setCategories(FXCollections.<String>observableArrayList
(Arrays.asList("n ame1", "name2"….)));
//Setting label to the axis
xAxis.setLabel("name of the axis ");
NumberAxis − 通过实例化此类,你可以定义(创建)X 轴或 Y 轴,每个值表示一个数字值。你可以使用此 Axis, Long, Double, BigDecimal 中的任何数字类型,等等。你可以按如下方式实例化此类来定义一个数字轴 −
NumberAxis − By instantiating this class, you can define (create) an X or Y axis along which each value represents a Numerical value. You can use any Number type with this Axis, Long, Double, BigDecimal, etc. You can define a Number axis by instantiating this class as follows −
//Defining the axis
NumberAxis yAxis = new NumberAxis();
//Setting labelto the axis
yAxis.setLabel("name of the axis");
Passing Data to XY Charts
所有 XY 图表都表示在 XY 平面中。要绘制图表中的一组点,我们需要指定一系列 XY 坐标。
All the XY charts are represented along the XY plane. To plot a set of points in a chart, we need to specify a series of XY coordinates.
javafx.scene.chart 包中的 <X,Y> 类是一个类,使用该类,你可以将数据发送到图表中。此类包含一个命名的序列的可观察列表。你可以按如下所示使用 XYChart.Series 类的 getData() 方法获取此列表:
The <X,Y> class of the javafx.scene.chart package is a class using which, you can send data to a chart. This class holds an observable list of named series. You can get this list using the getData() method of XYChart.Series class as shown below −
ObservableList list = series.getData();
其中, series 是 XYChart.Series 类的对象。你可以按如下方式使用 add() 方法将数据添加到此列表 −
Where, series is the object of the XYChart.Series class. You can add data to this list using the add() method as follows −
list.add(new XYChart.Data(x-axis data, y-axis data));
这两行可以一起写入,如下所示:
These two lines can be written together as shown below −
series.getData().add(new XYChart.Data(x-axis data, y-axis data));
下表对 JavaFX 提供的不同图表(类)进行了说明:
The following table gives a description of various charts (classes) provided by JavaFX −
S.No |
Chart & Description |
1 |
Pie ChartA pie-chart is a representation of values as slices of a circle with different colors. These slices are labeled and the values corresponding to each slice is represented in the chart. In JavaFX, a pie chart is represented by a class named PieChart. This class belongs to the package javafx.scene.chart. |
2 |
Line ChartA line chart or line graph displays information as a series of data points (markers) connected by straight line segments. Line Chart shows how the data changes at equal time frequency. In JavaFX, a line chart is represented by a class named LineChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a LineChart node in JavaFX. |
3 |
Area ChartArea charts are used to draw area based charts. It plots the area between the given series of points and the axis. In general, this chart is used to compare two quantities. In JavaFX, an Area chart is represented by a class named AreaChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a AreaChart node in JavaFX. |
4 |
Bar ChartA bar chart is used to represent grouped data using rectangular bars. The length of these bars depicts the values. The bars in the bar chart can be plotted vertically or horizontally. In JavaFX, a Bar chart is represented by a class named BarChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a BarChart node in JavaFX. |
5 |
Bubble ChartA bubble chart is used to plat three-dimensional data. The third dimension will be represented by the size (radius) of the bubble. In JavaFX, a Bubble chart is represented by a class named BubbleChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a BubbleChart node in JavaFX. |
6 |
Scatter ChartA scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables. In JavaFX, a Scatter chart is represented by a class named ScatterChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a ScatterChart node in JavaFX. |
7 |
Stacked Area ChartIn JavaFX, a Stacked Area chart is represented by a class named StackedAreaChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create an StackedAreaChart node in JavaFX. |
8 |
Stacked Bar ChartIn JavaFX, a Stacked Bar chart is represented by a class named StackedBarChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a StackedBarChart node in JavaFX. |
JavaFX - Layout Panes(Containers)
在场景中构造所有必需的节点后,我们通常会按顺序排列它们。
After constructing all the required nodes in a scene, we will generally arrange them in order.
容器内组件的这种排列称为容器的布局。我们也可以说我们遵循了一个布局,因为它包括将所有组件放置在容器内的特定位置。
This arrangement of the components within the container is called the Layout of the container. We can also say that we followed a layout as it includes placing all the components at a particular position within the container.
JavaFX 提供了几种预定义的布局,例如 HBox, VBox, Border Pane, Stack Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel 等。
JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.
上面提到的每个布局都由一个类表示,所有这些类都属于包 javafx.layout 。名为 Pane 的类是 JavaFX 中所有布局的基类。
Each of the above mentioned layout is represented by a class and all these classes belongs to the package javafx.layout. The class named Pane is the base class of all the layouts in JavaFX.
Creating a Layout
要创建布局,您需要 −
To create a layout, you need to −
-
Create node.
-
Instantiate the respective class of the required layout.
-
Set the properties of the layout.
-
Add all the created nodes to the layout.
Creating Nodes
首先,通过实例化其各自的类来创建 JavaFX 应用程序的必需节点。
First of all, create the required nodes of the JavaFX application by instantiating their respective classes.
例如,如果您希望在 HBox 布局中有一个文本字段和两个按钮(即播放和停止),您将必须首先创建这些节点,如以下代码块所示 −
For example, if you want to have a text field and two buttons namely, play and stop in a HBox layout - you will have to initially create those nodes as shown in the following code block −
//Creating a text field
TextField textField = new TextField();
//Creating the play button
Button playButton = new Button("Play");
//Creating the stop button
Button stopButton = new Button("stop");
Instantiating the Respective Class
在创建节点(并对它们完成所有操作)后,实例化所需布局的类。
After creating the nodes (and completing all the operations on them), instantiate the class of the required layout.
例如,如果您要创建 Hbox 布局,您需要按如下方式实例化此类。
For Example, if you want to create a Hbox layout, you need to instantiate this class as follows.
HBox hbox = new HBox();
Setting the Properties of the Layout
在实例化该类后,您需要使用其各自的 setter 方法设置该布局的属性。
After instantiating the class, you need to set the properties of the layout using their respective setter methods.
例如 − 如果你想在 HBox 布局中创建节点之间的间距,那么你需要给名为 spacing 的属性设置值。这可以通过使用 setter 方法 setSpacing() 来完成,如下所示 −
For example − If you want to set space between the created nodes in the HBox layout, then you need to set value to the property named spacing. This can be done by using the setter method setSpacing() as shown below −
hbox.setSpacing(10);
Adding the Shape Object to the Group
最后,你需要将形状的对象添加到组中,方法是将其作为构造函数的参数进行传递,如下所示。
Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below.
//Creating a Group object
Group root = new Group(line);
Layout Panes
以下是 JavaFX 提供的各种布局窗格(类)。这些类存在于 javafx.scene.layout 包中。
Following are the various Layout panes (classes) provided by JavaFX. These classes exist in the package javafx.scene.layout.
S.No |
Shape & Description |
1 |
HBoxThe HBox layout arranges all the nodes in our application in a single horizontal row. The class named HBox of the package javafx.scene.layout represents the text horizontal box layout. |
2 |
VBoxThe VBox layout arranges all the nodes in our application in a single vertical column. The class named VBox of the package javafx.scene.layout represents the text Vertical box layout. |
3 |
BorderPaneThe Border Pane layout arranges the nodes in our application in top, left, right, bottom and center positions. The class named BorderPane of the package javafx.scene.layout represents the border pane layout. |
4 |
StackPaneThe stack pane layout arranges the nodes in our application on top of another just like in a stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it. The class named StackPane of the package javafx.scene.layout represents the stack pane layout. |
5 |
TextFlowThe Text Flow layout arranges multiple text nodes in a single flow. The class named TextFlow of the package javafx.scene.layout represents the text flow layout. |
6 |
AnchorPaneThe Anchor pane layout anchors the nodes in our application at a particular distance from the pane. The class named AnchorPane of the package javafx.scene.layout represents the Anchor Pane layout. |
7 |
TilePaneThe Tile Pane layout adds all the nodes of our application in the form of uniformly sized tiles. The class named TilePane of the package javafx.scene.layout represents the TilePane layout. |
8 |
GridPaneThe Grid Pane layout arranges the nodes in our application as a grid of rows and columns. This layout comes handy while creating forms using JavaFX. The class named GridPane of the package javafx.scene.layout represents the GridPane layout. |
9 |
FlowPaneThe flow pane layout wraps all the nodes in a flow. A horizontal flow pane wraps the elements of the pane at its height, while a vertical flow pane wraps the elements at its width. The class named FlowPane of the package javafx.scene.layout represents the Flow Pane layout. |
JavaFX - CSS
Cascading Style Sheets ,也称为 CSS,是一种简单的设计语言,目的是简化网页呈现的过程。
Cascading Style Sheets, also referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable.
CSS 处理网页的外观和感觉部分。使用 CSS,您可以控制文本颜色、字体样式、段落间距、列大小和布局。此外,您还可以控制所使用的背景图像或颜色、布局设计、针对不同设备的显示差异和屏幕大小以及各种其他效果。
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, style of fonts, spacing between paragraphs, size of columns and layout. Apart from these, you can also control the background images or colors that are used, layout designs, variations in display for different devices and screen sizes as well as a variety of other effects.
CSS in JavaFX
JavaFX 为您提供了使用 CSS 来提升应用程序外观和感觉的功能。包 javafx.css 包含用于为 JavaFX 应用程序应用 CSS 的类。
JavaFX provides you the facility of using CSS to enhance the look and feel of the application. The package javafx.css contains the classes that are used to apply CSS for JavaFX applications.
CSS 包含浏览器解释的样式规则,然后将其应用到您文档中相应的元素。
A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding elements in your document.
样式规则由三部分组成,即-
A style rule is made of three parts, which are −
-
Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table>, etc.
-
Property − A property is a type of attribute of the HTML tag. In simpler terms, all the HTML attributes are converted into CSS properties. They could be color, border, etc.
-
Value − Values are assigned to properties. For example, a color property can have value either red or #F1F1F1, etc.
您可以按如下方式设置 CSS 样式规则语法 −
You can put CSS Style Rule Syntax as follows −
selector { property: value }
JavaFX 使用的默认样式表是 modena.css 。它位于 JavaFX 运行时 jar 中。
The default style sheet used by JavaFX is modena.css. It is found in the JavaFX runtime jar.
Adding Your own Style Sheet
您可以按照以下方式将自己的样式表添加到 JavaFX 中的场景:
You can add your own style sheet to a scene in JavaFX as follows −
Scene scene = new Scene(new Group(), 500, 400);
scene.getStylesheets().add("path/stylesheet.css");
Adding Inline Style Sheets
您还可以使用 setStyle() 方法添加内联样式。这些样式仅由键值对组成,并且适用于对其进行设置的节点。以下是在按钮中设置内联样式表的示例代码。
You can also add in-line styles using the setStyle() method. These styles consist of only key-value pairs and they are applicable to the nodes on which they are set. Following is a sample code of setting an inline style sheet to a button.
.button {
-fx-background-color: red;
-fx-text-fill: white;
}
Example
假设我们开发了一个显示带有文本字段、密码字段、两个按钮的表单的 JavaFX 应用程序。默认情况下,此表单的外观如下图所示 −
Assume that we have developed an JavaFX application which displays a form with a Text Field, Password Field, Two Buttons. By default, this form looks as shown in the following screenshot −
以下程序是演示如何在 JavaFX 中向上述应用程序添加样式的示例。
The following program is an example which demonstrates how to add styles to the above application in JavaFX.
将此代码保存在名为 CssExample.java 的文件中
Save this code in a file with the name CssExample.java
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class CssExample extends Application {
@Override
public void start(Stage stage) {
//creating label email
Text text1 = new Text("Email");
//creating label password
Text text2 = new Text("Password");
//Creating Text Filed for email
TextField textField1 = new TextField();
//Creating Text Filed for password
PasswordField textField2 = new PasswordField();
//Creating Buttons
Button button1 = new Button("Submit");
Button button2 = new Button("Clear");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(400, 200);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(button1, 0, 2);
gridPane.add(button2, 1, 2);
//Styling nodes
button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
text1.setStyle("-fx-font: normal bold 20px 'serif' ");
text2.setStyle("-fx-font: normal bold 20px 'serif' ");
gridPane.setStyle("-fx-background-color: BEIGE;");
// Creating a scene object
Scene scene = new Scene(gridPane);
// Setting title to the Stage
stage.setTitle("CSS Example");
// Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac CssExample.java
java CssExample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.