FXMLLoader如何通过FXID访问组件? [英] FXMLLoader how to access the components by FXID?
问题描述
我正在试图弄清楚如何使用JavaFx。
我在Scene Builder中构建了应用程序界面。但我无法访问该组件,因为所有组件都加载到Parent中。
I'm trying to figure out how to work with JavaFx. I built the application interface in Scene Builder. But I can not get access to the component, since all loaded into the Parent.
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
如果我在Pane上更改Parent,我可以访问getChildren(),但是目前尚不清楚如何获得控制权如果我知道fx:id ...
If I change "Parent" on "Pane" I can get access to the getChildren(), but it is not clear how to get control if i know fx:id...
问题甚至更简单。我在Scene Builder中添加了Label或TextField。如果我知道fx:id,我如何从代码中更改它的文本?
The question is even simpler. I added Label or TextField in Scene Builder. How do I change it's text from the code if I know the fx:id?
我绝望。
推荐答案
您应该为FXML文档创建一个控制器类,您可以在其中执行涉及UI组件所需执行的任何功能。您可以使用 @FXML
注释该类中的字段,它们将由 FXMLLoader
填充,与<$ c匹配$ c> fx:id 字段名称的属性。
You should create a controller class for your FXML document, in which you can perform any functionality you need to perform involving the UI components. You can annotate fields in that class with @FXML
and they will be populated by the FXMLLoader
, matching the fx:id
attribute to the field name.
Work through the tutorial for more details, and have a look at the Introduction to FXML documentation.
简单示例:
Sample.fxml:
Sample.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="SampleController">
<Label fx:id="countLabel"/>
<Button fx:id="incrementButton" text="Increment" onAction="#increment"/>
</VBox>
SampleController.java:
SampleController.java:
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class SampleController {
private int count = 0 ;
@FXML
private Label countLabel ;
@FXML
private void increment() {
count++;
countLabel.setText("Count: "+count);
}
}
SampleMain.java:
SampleMain.java:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class SampleMain extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("Sample.fxml")), 250, 75);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这篇关于FXMLLoader如何通过FXID访问组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!