Simple use of JavaFX\FXML\CSS

The blogger is an amateur, not a developer.
The four files mentioned below:
Main.java FxmlController.java FXML file (.fxml) test.css

src{
    
    
	fx{
    
    
		Main.java
		FxmlController.java	}
	fxml{
    
    
		FXML文件(test.fxml)	}
	css{
    
    
		test.css } }

0.MVC framework

In the
classic MVC model of Model View Controller , M refers to the business model, V refers to the user interface, and C refers to the controller. The purpose of using MVC is to separate the implementation code of M and V, so that the same program can use different performances. form. (-Baidu Encyclopedia: MVC Framework )

Quoting the comment from the b station video @東個雪清Reply @Computer PlayerRain: link


8, HTML------------->FXML: structure (artist)


9, CSS----- ---------->CSS: Appearance rights (artist)


10. JavaScript-------->Controller.java: Behavior (developer)

1. Selector

The selector in the JavaFX CSS file: (rough use, no in-depth content)
1. ID selector prefixed with #:
#id{ …/* CSS code format with -fx prefix written by line: attribute : Value*/ …}
Select the component with ID set according to ID.
E.g:

#fxmlButton1{
    
    
    -fx-font-size: 18;
    -fx-background-color: black;
    -fx-text-fill:Snow;
}

2. Class and type selectors prefixed by .:
.className{ …/* CSS code format with -fx prefix written by line: attribute: value*/…}
Change a class of components at the same time.
E.g:

.button{
    
    
    -fx-font-size: 18;
    -fx-background-color: black;
    -fx-text-fill:Snow;
}

3. Add the style when responding to events to the component: (pseudo-class selector)
selector: pseudo-class {…/* CSS code format with -fx prefix written by line: attribute: value*/ …}
For example:

/* 鼠标在按钮上悬停 对所有按钮都生效 */
.button:hover{
    
    
	-fx-background-color: blue;
}

Note: Syntax errors in the css file can only be reported when the relevant code is called.

Reference:
[ JavaFX-CSS selector ]
https://blog.csdn.net/yye894817571/article/details/79416036

2. Specify the controller fx:controller in the FXML file

In the FXML file, add the specified controller FxmlController.java statement at the root node:
fx:controller="package name.FxmlController"
(load only once)
For example:

<AnchorPane fx:controller="fxControl.FxmlController" ... >

In this way, the control of the components can be realized in the FxmlController.java class.
But in the title 6 below, you can know that you can also write the event response in Main.java.

3.FxmlController.java

@FXML annotation tag in fxmlController.java: The
Main.java file loads the FXML file, and the FXML file instantiates the object.
For example:

public class FxmlController {
    
    

	@FXML
	private Button fxmlbutton;
	// 这个fxmlbutton已经被实例化了,
	// 实例化的对象就是FXML中以“fxmlbutton”为fx:id的组件。
	// fxmlbutton得到了FXML文件中<Button fx:id="fxmlbutton">的引用。
	
	public FxmlController(){
    
    
	}
	
	@FXML
	private void initialize(){
    
    
		System.out.println(fxmlbutton.getText()); //打印按钮上的文本
	}
}

Correct nonsense:
Simply put, the @FXML tag corresponds to the content of the FXML file. In fact, it can be executed correctly even without this tag for public, but this tag must be used for private.
And follow the normative writing method should add @FXML tag, in order to be able to carry out while loading.

4. Load the FXML file

Add the statement to load the FXML file in the start method or the stop method in the Main.java file: the
FXMLLoader object is required:
FXMLLoader fxLoader = new FXMLLoader();
For example:

FXMLLoader fxLoader = new FXMLLoader();
URL url = fxLoader.getClassLoader().getResource("fxml/test.fxml");//此处要用getClassLoader(),路径从src下开始,fx包名前不加"/"
fxLoader.setLocation(url);
AnchorPane root = (AnchorPane) fxLoader.load();

Or equivalently written as:

AnchorPane root = FXMLLoader.load(getClass().getResource("test.fxml"));//此处用getClass()

Load() method prototype: (at least URL parameters)

public static <T> T load(URL location,
                         ResourceBundle resources,
                         BuilderFactory builderFactory)
                  throws IOException

5. Introduce CSS files

Introduce the CSS file statement in the start method or the stop method in the Main.java file:
use the Scene class object to load:
for example:

Scene scene = new Scene(root);
URL url_css = this.getClass().getClassLoader().getResource("/CSS/test.css");
scene.getStylesheets().add(url_css.toExternalForm());

Or equivalently written as:

Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/CSS/test.css").toExternalForm());

6. Add incident response

For example, add an event to <Button fx:id="fxmlbutton"> in FXML.
Three methods:
1. (Recommended) Realize control in Main.java through an instantiated object of the controller class FxmlController:
need to be in Main.java Instantiate an FxmlController class object, such as fc, and then use the get method written by yourself in the FxmlController class (get method does not need to add @FXML) to return the component.
Regarding multiple listeners, if you write an action in Main.java after instantiating the object through Method 3, it will replace (combined by x:controller="fxControl.FxmlController" and onAction="#buttonOnAction") in Method 2 Actions written in FxmlController.java. If there are repeated actions in the same file, the method written later will overwrite the method written first.
What you need to do in this way is to write the get method of the component in FxmlController.java, and then call the get method to obtain the reference of the component by instantiating the FxmlController object in Main.java, and then write the action.
The method of instantiating the FxmlController object: return the FxmlController instance through the instantiated object.getController method of the FXMLLoader class.
For example:
FxmlController.java file:

	@FXML
    public Button button1;

	//相应的get方法
	//button1的get方法,返回Button类
	public Button getButton1() {
    
    
        return button1;
    }

Main.java file:

	//加载fxml文件
    FXMLLoader fxLoader = new FXMLLoader();
    URL url = fxLoader.getClass().getResource("fileURL");
    fxLoader.setLocation(url);
    AnchorPane root = (AnchorPane) fxLoader.load();
    //把FxmlHandler类实例化:
    FxmlHandler fxmlHandler = fxLoader.getController();
    //获取组件的引用
    Button button1= fxmlHandler.getButton1();
    
    /* 然后在下面写响应的动作 */

	button1.setOnAction(new EventHandler<ActionEvent>() {
    
    
          @Override
          public void handle(ActionEvent event) {
    
    
              
          }
    });

The reason why this way of writing is recommended is that it is easy to handle the mutual calls between components.

2. Directly specify in the form of attributes in the components of the FXML file, so that after specifying, write the event response in the file set by fx:controller in FXML:
The code in the FXML file:

<AnchorPane fx:controller="fxControl.FxmlController" ...>
	<Button onAction="#buttonOnAction" ...>
	...
</AnchorPane>

The code in FxmlController.java:

@FXML
private void buttonOnAction(){
    
    
	...
}

3. You can get the component by using Button bu = root.lookup("#fxmlbutton"); in Main.java, and then write the event response in Main.java:
The code in the FXML file:

<AnchorPane ...>
	<Button fx:id="fxmlbutton" ...>
	...
</AnchorPane>

The code in Main.java:

Button bu = root.lookup("#fxmlbutton");

7. Where can I write CSS statements with -fx prefix?

1. A separate .css file (after writing, you need to import the css file into the java file)
follow the CSS syntax, search by yourself or refer to the official JavaFX CSS document .
2. It can be written directly in the setStyle() method called by the javafx component in the Main.java file, wrapped in quotation marks.
E.g:

button.setStyle("-fx-background-color: black;" +
                "-fx-text-fill:Snow;");

3. Write in the <style></style> tag of the component in the FXML file.
E.g:

<AnchorPane ...>
	<Button ...>
		<style>
			-fx-background-color: black;
			-fx-text-fill:Snow;
		</style>
		...
	</Button>
	...
</AnchorPane>

Reference [ Official JavaFX CSS Document: JavaFX CSS Reference Guide: ]
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
Reference [ Bilibili Video: JavaFX Video Tutorial No. 119 Lesson, simple use of CSS ]
https://www.bilibili.com/video/BV1pb411s7cd

8. SceneBuilder visual graphics editing tool

SceneBuilder visual graphics editing tool:
download address: select the corresponding version to download:
(1) gluonhq.com download :
https://gluonhq.com/products/scene-builder/
(2) www.oracle.com download :
https:// www.oracle.com/java/technologies/javafxscenebuilder-1x-archive-downloads.html
Import in the development tool:
(1) Eclipse reference: [JavaFx tutorial] Part 1: Scene Builder
(2) IDEA reference: Use scene builder in IDEA
Use:
Right-click on the .fxml file in the development tool software and choose to open it in SceneBuilder.

9. The problem of FXMLLoader loading file path

The files mentioned above are all in a certain package under the same src folder. If you change the location of the image resource folder, CSS, and FXML files, it will become parallel with the src file. Modify the address, otherwise an error will be reported. .
Moreover, the address in the FXML file should also be modified.
Moreover, even if you can click to jump by holding down ctrl on IDEA, it does not mean that the execution is correct. Similarly, not being able to jump does not mean it is wrong.
Example: (the positions of src, css, and fxml are aligned) In
the start method of Main.java:
HostServices host = this.getHostServices();
String css = host.resolveURI(host.getDocumentBase(),"css/test1.css");
String fxml = host.resolveURI(host.getDocumentBase(),"fxml/test1.fxml");
FXMLLoader fxLoader = new FXMLLoader();
URL url_fxml = new URL(fxml);
fxLoader.setLocation(url_fxml);
AnchorPane root = fxLoader .load();
Scene scene = new Scene(root);
scene.getStylesheets().add(css);
primaryStage.show(); A
picture address of FXML file:
<Image url="@…/res/img/test1.png" />

Other references:
[JavaFX API document: (Currently the latest is 15, the number 15 in the modification path can be changed)]
https://openjfx.cn/javadoc/15/

[FXML + CSS development login interface] https://blog.csdn.net/LiHaoYang11/article/details/71106755

[Introduction to JavaFX (5): Use CSS styles to beautify your UI controls] https://blog.csdn.net/theonegis/article/details/50189443

[Solutions for errors in quoting CSS files in JavaFX] https://blog.csdn.net/weixin_43898956/article/details/102912443?utm_medium=distribute.pc_relevant.none-task-blog-utm_term-10&spm=1001.2101.3001.4242

[JavaFX-not many are not long-winded, I must have a HelloWorld at the beginning] https://www.cnblogs.com/oscar1987121/p/9019644.html

[Detailed explanation of FXController of JavaFX] https://blog.csdn.net/wingfourever/article/details/41349855

Guess you like

Origin blog.csdn.net/qq_43750882/article/details/110679531