java - 有没有办法在控制器中初始化一个变量,并在 FXML 中使用它?
问题描述
所以,我在 FXML 中制作了一个菜单,并且我使用了一个 Group,所以我必须设置一个 prefWidth 否则它看起来很奇怪。为此,我想在控制器中使用屏幕宽度初始化一个变量,然后在 FXML 中设置菜单时使用宽度变量。但我就是找不到办法做到这一点。
概括这个问题,我想在控制器中初始化一个变量,然后在 FXML 中使用它,如下所示:
[控制器]
package sample;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@Override
public void initialize (URL url, ResourceBundle resourceBundle) {
String text = "test";
}
}
[FXML]
<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>
<BorderPane>
<center>
<label text="<!--use var 'text' here-->"/>
</center>
</BorderPane>
我知道,还有其他方法可以做到这一点(比如 id-ing 并在控制器中设置文本),但我只是想看看是否可以这样做。
解决方案
使用属性代替变量。将其放在班级级别。
public class Controller implements Initializable {
private String text; // or use binding property
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
text = "hello";
}
}
FXML
<BorderPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml">
<center>
<Label text="${controller.text}"/>
</center>
</BorderPane>
推荐阅读
- php - 回显字符串并不总是显示单个引号
- android-studio - 连接失败(连接重置)。请检查网络连接,然后在 Android Studio 中重试
- python - Tensorflow Keras 预测返回错误形状的输出
- python - 如何使用 Windows 10 在 anaconda 上安装 boost python
- lua - 需要帮助检测我的 lua 脚本中的游戏灯光
- javascript - 将 JSON 数据传递到另一个屏幕
- python - 有没有办法遍历 Gensim 的 Word2Vec 的向量?
- swift - 如何在 SwiftUI 中检测空内容作为输入内容?
- python-3.x - PyTelegramBotAPI 将最后一个帖子从频道转发到 user_id
- c - 除了无符号整数之外检查溢出的函数