java 如何通过 id 更改 fxml 标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32806068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change fxml lable text by id
提问by Oshrib
I have Label on my fxml file:
我的 fxml 文件上有标签:
<children>
<Label fx:id="lblTest" text="Label" />
</children>
How can i change the text from "Label" to "Hello" from the main/controller java file?
如何将主/控制器 java 文件中的文本从“标签”更改为“Hello”?
I just started to learn the basics of JavaFX and i am not sure if it possible
我刚开始学习 JavaFX 的基础知识,我不确定是否可能
回答by aw-think
Problem
问题
You want to set the text on a label that is part of FXML/Controller/MainApp
您想在属于 FXML/Controller/MainApp 的标签上设置文本
Solution
解决方案
Normally you have three files:
通常你有三个文件:
- FXML-Document
- FXML-Controller
- Class that extends Application and overrides the start method
- FXML-文档
- FXML-控制器
- 扩展 Application 并覆盖 start 方法的类
A little Example:
一个小例子:
LabelText.java
标签文本文件
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class LabelText extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
FXMLDocument.fxml
FXML文档.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40" fx:controller="labeltext.FXMLDocumentController">
<children>
<Label fx:id="lblTest" layoutX="126.0" layoutY="92.0" minHeight="16" minWidth="69" />
</children>
</AnchorPane>
FXMLDocumentController.java
文件控制器.java
package labeltext;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class FXMLDocumentController {
@FXML
private Label lblTest;
@FXML
private void initialize() {
lblTest.setText("I'm a Label.");
}
}
And that's it.
就是这样。
回答by Oshrib
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Label lblData = (Label) root.lookup("#lblTest");
if (lblData!=null) lblData.setText("bye");