Introduction to JavaFX
When we mention Java's graphical interface library, we usually hear Swing, or older AWT, including the two introduced in many books. Many schools and training classes also teach these two technologies. But in fact, both technologies have been outdated for a long time. Although it is not difficult to learn Swing, it is actually very difficult to write the interface using it. Because its interface and code are not separated, the code must be filled with a large number of coordinates when writing, and it is extremely difficult to modify. The best thing in this regard is Microsoft's WPF, and I can only say who can use it and who knows it.
Of course, although writing client graphics programs is Java's weakness, Java has not given up on this effort. The JavaFX introduced today is the latest technology for Java to write graphical interface programs. If you are planning to write graphical interface programs in Java without any historical burden, it is highly recommended to use JavaFX.
This is the resources and documentation on JavaFX on Oracle's official website.
This is an official sample program, we can refer to the JavaFX section to learn how to use it. Below is one of the fractal JavaFX programs. Clicking on the numbers above can enter different microscopic displays. It feels like watching the microscopic world of viruses, which is very shocking.
How to install
As long as you have the latest version of JDK 8 installed, you can use the JavaFX library. If it is not installed, then start installing it quickly.
Get started quickly
The first program
Create a new project, then write the following class, and then compile and run to see the results. There is no need to explain this program. If you have experience in learning Swing and other graphical interface frameworks, it should be very easy to understand this code. Of course, since JavaFX is a new thing, I also use the new feature of Java 8 - lambda expressions.
package yitian.javafxsample;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.StackPane;import javafx.stage.Stage;public class HelloJavaFX extends Application {@Override public void start(Stage primaryStage) throws Exception {Button btn = new Button();btn.setText("Hello, world");btn.setOnAction(event -> {System.out.println("Hello, world!");});StackPane root = new StackPane();root.getChildren().add(btn);Scene scene = new Scene(root, 300, 250);primaryStage.setTitle("Hello World!");primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {launch(args);}}The running screenshot is as follows.
User input
This program can be used to handle user login situations. The code is as follows, and the important parts have been commented. The last part of the code uses the setOnAction function to add a click event to the button, and the text will be displayed when the button is clicked.
public class UserInput extends Application {@Override public void start(Stage primaryStage) throws Exception {//Grid layout GridPane grid = new GridPane();grid.setAlignment(Pos.CENTER);//Grid vertical spacing grid.setHgap(10);//Grid horizontal spacing grid.setVgap(10);grid.setPadding(new Insets(25, 25, 25, 25));//New scene Scene scene = new Scene(grid, 300, 275);primaryStage.setScene(scene);//Add the titleText sceneitle = new Text("Welcome");scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));grid.add(scenetitle, 0, 0, 2, 1);//Add tags and text boxesLabel userName = new Label("Username:");grid.add(userName, 0, 1);TextField userTextField = new TextField();grid.add(userTextField, 1, 1);//Add tags and password boxes Label pw = new Label("Password:");grid.add(pw, 0, 2);PasswordField pwBox = new PasswordField();grid.add(pwBox, 1, 2);//Add submission button Button btn = new Button("Login");HBox hbBtn = new HBox(10);hbBtn.setAlignment(Pos.BOTTOM_RIGHT);hbBtn.getChildren().add(btn);grid.add(hbBtn, 1, 4);//Submit text prompt final Text actiontarget = new Text();grid.add(actiontarget, 1, 6);btn.setOnAction(event -> {actiontarget.setFill(Color.FIREBRICK);actiontarget.setText("Login");});primaryStage.setTitle("JavaFX Welcome");primaryStage.show();}public static void main(String[] args) {launch(args);}}The screenshot of the program running is as follows.
This program is actually not difficult, it uses the grid layout and then adds each element to the grid. For the attribute meaning of grid layout, please refer to the official figure.
Designing a user interface with FXML
Modern graphical interface frameworks support separating the interface and code, and the more commonly used descriptive language is XML, such as QML for QT and XAML for WPF. Of course, JavaFX also has a similar language called FXML. If you need to know FXML in detail, you can refer to the article Introduction to FXML on the official website of Oracle.
Let’s rewrite the above small example in FXML, and each part is commented. If you have learned other similar descriptive languages, you will find that these are actually similar. The only thing to note is the fx:controller attribute in the layout, which specifies a controller, and the function of the controller is to write the corresponding code of the interface.
<?xml version="1.0" encoding="UTF-8"?><!--Import class--><?import javafx.geometry.Insets?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><?import javafx.scene.text.Font?><?import javafx.scene.text.Text?><!--Set layout--><GridPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="yitian.javafxsample.Controller" prefHeight="400.0" prefWidth="600.0" alignment="center" hgap="10" vgap="10"> <padding> <Insets top="25" right="25" bottom="10" left="25"/> </padding> <!--Welcome text--> <Text text="Welcome" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2"> <font> <Font name="Consolas" size="20"/> </font> </Text> <Label text="Username:" GridPane.columnIndex="0" GridPane.rowIndex="1"/> <TextField GridPane.columnIndex="1" GridPane.rowIndex="1"/> <Label text="password:" GridPane.columnIndex="0" GridPane.rowIndex="2"/> <PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2"/> <!--Button and prompt text--> <HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="1" GridPane.rowIndex="4"> <Button text="Show Password" onAction="#showPasswordButton"/> </HBox> <Text fx:id="hintText" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.halignment="RIGHT" GridPane.rowIndex="6"/></GridPane>
Below is the controller corresponding to this FXML file, which is a standard Java class. The ID specified by the fx:id attribute in FXML can be declared as a class field in the controller, through which you can interact with the interface components. By the same token, the event handler declared by onAction is a method in the controller. Note that these fields and methods need to be annotated using @FXML annotation.
import javafx.event.ActionEvent;import javafx.fxml.FXML;import javafx.scene.control.PasswordField;import javafx.scene.text.Text;public class Controller {@FXML private Text hintText;@FXML private PasswordField passwordField;@FXML protected void showPasswordButton(ActionEvent event) {hintText.setText("Show password:" + passwordField.getText());}}The last thing to modify is the main program. In the main program, you need to use FXMLLoader to load FXML resources, and the other parts have not changed much.
public class UseFxml extends Application {@Override public void start(Stage primaryStage) throws Exception {Parent root = FXMLLoader.load(getClass().getResource("ui.fxml"));Scene scene = new Scene(root, 300, 275);primaryStage.setTitle("Use FXML");primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {launch(args);}}The screenshot of the program running is as follows.
If you want to modify component styles, JavaFX provides a CSS interface, allowing us to modify styles directly using CSS files. First, you need to add a reference to the corresponding style sheet in the FXML file. The @ in front of the file name means that the CSS file and the FXML file are in the same directory.
<GridPane> <stylesheets> <URL value="@style.css"/> </stylesheets><GridPane/>
Style sheets are similar to ordinary style sheets, except that JavaFX-specific prefix- is required.
#btnShowPassword { -fx-background-color: deeppink;}The ID selector is used above, so correspondingly, ID attributes are also required in FXML.
<Button id="btnShowPassword" text="ShowPassword" onAction="#showPasswordButton"/>
The program after customization is shown in the figure. I have only simply modified the background color of the button. In fact, there are many styles that can be changed, including program background, etc. Students who are interested can try it on their own.
Summarize
The above is all about this article about a preliminary understanding of javafx. If any student wants to use Java to write graphical interface programs, you can consider using JavaFX, which is a very good choice. Hope it will be helpful to everyone. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!