如何从运行时添加的 javafx TextField 获取文本?
How can I get the text from a javafx TextField added at runtime?
我在场景中有两个按钮,一个触发方法 newFields()
,它在 HBox
中生成两个新的 TextField
,另一个通过 getText()
方法,我希望它能获取输入的文本。
sample.fxml:
<VBox prefHeight="275.0" prefWidth="300.0" fx:id="pane">
<children>
<Button layoutX="6.0" layoutY="14.0" mnemonicParsing="false" onAction="#newFields" text="New Fields" />
<Button layoutX="6.0" layoutY="53.0" mnemonicParsing="false" onAction="#getTexts" text="Get Texts" />
</children>
</VBox>
Controller.java:
public class Controller {
@FXML VBox pane;
@FXML void newFields(){
HBox hb = new HBox();
pane.getChildren().add(hb);
TextField tf = new TextField();
tf.setPromptText("Name here");
TextField tf2 = new TextField();
tf2.setPromptText("Age here");
hb.getChildren().addAll(tf, tf2);
}
@FXML void getTexts(){
ObservableList<Node> childsVB = pane.getChildren();
Node hb = childsVB.get(2);
hb.getChildren();//Cannot resolve method
}
}
我有包含 Texfield
的 HBox
的节点,但我被困在那里,我试图获取 HBox
的子节点,但 IDE 抛出错误。
我是这里的新用户,我确实在寻找答案但没有成功。
提前致谢。
Node
没有 getChildren()
方法。你应该使用铸造。
变化:
Node hb = childsVB.get(2);
至:
HBox hb = (HBox)childsVB.get(2);
或使用 Pane class:
Pane pane = (Pane)childsVB.get(2);
我在场景中有两个按钮,一个触发方法 newFields()
,它在 HBox
中生成两个新的 TextField
,另一个通过 getText()
方法,我希望它能获取输入的文本。
sample.fxml:
<VBox prefHeight="275.0" prefWidth="300.0" fx:id="pane">
<children>
<Button layoutX="6.0" layoutY="14.0" mnemonicParsing="false" onAction="#newFields" text="New Fields" />
<Button layoutX="6.0" layoutY="53.0" mnemonicParsing="false" onAction="#getTexts" text="Get Texts" />
</children>
</VBox>
Controller.java:
public class Controller {
@FXML VBox pane;
@FXML void newFields(){
HBox hb = new HBox();
pane.getChildren().add(hb);
TextField tf = new TextField();
tf.setPromptText("Name here");
TextField tf2 = new TextField();
tf2.setPromptText("Age here");
hb.getChildren().addAll(tf, tf2);
}
@FXML void getTexts(){
ObservableList<Node> childsVB = pane.getChildren();
Node hb = childsVB.get(2);
hb.getChildren();//Cannot resolve method
}
}
我有包含 Texfield
的 HBox
的节点,但我被困在那里,我试图获取 HBox
的子节点,但 IDE 抛出错误。
我是这里的新用户,我确实在寻找答案但没有成功。
提前致谢。
Node
没有 getChildren()
方法。你应该使用铸造。
变化:
Node hb = childsVB.get(2);
至:
HBox hb = (HBox)childsVB.get(2);
或使用 Pane class:
Pane pane = (Pane)childsVB.get(2);