连接Javafx fx:Id [英] Concatenate Javafx fx:Id
本文介绍了连接Javafx fx:Id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 JavaFX 的新手,目前正在尝试为学校项目执行日历应用程序。我想知道是否有办法连接 fx:id
这样的
I'm kinda new to JavaFX and currently trying to do a Calendar application for a school project. I was wondering if there was a way to concatenate a fx:id
such a
@FXML
private Label Box01;
(In function)
String ExampleNum = "01";
(Box+ExampleNum).setText("Test");
推荐答案
除了@jewelsea提到的方法,这里有还有2种方法:
In addition to the methods mentioned by @jewelsea here are 2 more ways to do this:
-
创建&注入一个
Map
,其中包含来自fxml的值:
Create & inject a
Map
containing the boxes as values from the fxml:
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxml.Controller">
<children>
<Label text="foo" fx:id="a"/>
<Label text="bar" fx:id="b"/>
<Spinner fx:id="number">
<valueFactory>
<SpinnerValueFactory.IntegerSpinnerValueFactory min="1" max="2"/>
</valueFactory>
</Spinner>
<Button text="modify" onAction="#modify"/>
<fx:define>
<HashMap fx:id="boxes">
<box1>
<fx:reference source="a"/>
</box1>
<box2>
<fx:reference source="b"/>
</box2>
</HashMap>
</fx:define>
</children>
</VBox>
控制器
public class Controller {
private Map<String, Label> boxes;
@FXML
private Spinner<Integer> number;
@FXML
private Label box1;
@FXML
private Label box2;
@FXML
private void modify(ActionEvent event) {
boxes.get("box"+number.getValue()).setText("42");
}
}
通过<$ FXMLLoader
的c $ c> namespace ,这是 Map< String,Object>
将 fx:id
映射到关联的对象
s到控制器:
Pass the namespace
of the FXMLLoader
, which is a Map<String, Object>
mapping fx:id
s to the associated Object
s, to the controller:
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxml.Controller">
<children>
<Label text="foo" fx:id="box1"/>
<Label text="bar" fx:id="box2"/>
<Spinner fx:id="number">
<valueFactory>
<SpinnerValueFactory.IntegerSpinnerValueFactory min="1" max="2"/>
</valueFactory>
</Spinner>
<Button text="modify" onAction="#modify"/>
</children>
</VBox>
控制器
public class Controller implements NamespaceReceiver {
private Map<String, Object> namespace;
@FXML
private Spinner<Integer> number;
@FXML
private Label box1;
@FXML
private Label box2;
@FXML
private void modify(ActionEvent event) {
((Label)namespace.get("box" + number.getValue())).setText("42");
}
@Override
public void setNamespace(Map<String, Object> namespace) {
this.namespace = namespace;
}
}
public interface NamespaceReceiver {
public void setNamespace(Map<String, Object> namespace);
}
加载fxml的代码:
public static <T> T load(URL url) throws IOException {
FXMLLoader loader = new FXMLLoader(url);
T result = loader.load();
Object controller = loader.getController();
if (controller instanceof NamespaceReceiver) {
((NamespaceReceiver) controller).setNamespace(loader.getNamespace());
}
return result;
}
这篇关于连接Javafx fx:Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文