gpt4 book ai didi

java - 组件构造函数参数 fxml javafx

转载 作者:搜寻专家 更新时间:2023-11-01 01:25:48 24 4
gpt4 key购买 nike

首先,我给你我的代码。

组件

public class Schuiver extends VBox{

private final SchuiverCompanion companion;

public Schuiver(String text) {
try {
FXMLLoader loader = new FXMLLoader(
Schuiver.class.getResource("nuleenschuiver.fxml"));
loader.setRoot(this);
this.companion = new SchuiverCompanion();
loader.setController(companion);
companion.setText(text);

loader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}

}
}

组件 Controller

public class SchuiverCompanion {

public TextField kleurveld;
public Label titel;
public Slider schuiver;

public void initialize() {
kleurveld.textProperty().bindBidirectional(schuiver.valueProperty(),
new NumberStringConverter());
}

public void setText(String text){
titel.setText(text);
}

}

COMPONENTFXML

 <?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<fx:root fx:id="vbox" minHeight="-1.0" prefHeight="-1.0" prefWidth="-1.0" spacing="5.0" type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="kleurenkiezer.SchuiverCompanion">
<children>
<Label fx:id="titel" alignment="TOP_LEFT" text="Hier een titel" />
<HBox prefHeight="44.0" prefWidth="299.0">
<children>
<Slider fx:id="schuiver" prefHeight="14.0" prefWidth="215.0" />
<TextField fx:id="kleurveld" prefHeight="25.0" prefWidth="76.0" />
</children>
</HBox>
</children>
</fx:root>

如您所见,我的组件请求一个将放置在标签中的字符串,问题是,如果您创建这样的对象,则无法在 fxml 文件中传递参数:

 <Schuiver  fx:id="red" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<Schuiver fx:id="blue" GridPane.columnIndex="1" GridPane.rowIndex="1"/>

所以我的问题是,如果我使用我的组件启动程序,我该如何更改标签“标题”的文本?标题应该类似于 fix:id。

最佳答案

在 JavaFX 8 中,您可以通过使用 @NamedArg(...) 注释构造函数参数来做到这一点:

public class Schuiver extends VBox{

private final SchuiverCompanion companion;

public Schuiver(@NamedArg("text") String text) {

// ...
}

}

然后就可以在FXML中使用参数了:

<Schuiver  fx:id="red" text="red" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<Schuiver fx:id="blue" GridPane.columnIndex="1" GridPane.rowIndex="1">
<text>
<String fx:value="blue" />
</text>
</Schuiver>

关于java - 组件构造函数参数 fxml javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com