我在FXMLController中有一个TextField和一个按钮,在SecondFXMLController中有一个标签
现在我想在SecondFXMLController中获取TextField的值
注意:将在同一阶段加载两个fxml文件
FXMLController:
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@FXML
private Button button;
@FXML
private TextField firstField;
@FXML
private AnchorPane first;
private int a;
@FXML
private void handleButtonAction(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("SecondFXML.fxml"));
first.getChildren().setAll(pane);
}
public String setTo() {
System.out.println("In setTo function");
System.out.println(firstField.getText());
return firstField.getText();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
SecondFXMLController:
public class SecondFXMLController implements Initializable
{
@FXML
private Label secondField;
private String f;
private AnchorPane pane;
private FXMLDocumentController con;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
FXMLLoader fxml = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
try {
pane = fxml.load();
con = fxml.getController();
f = con.setTo();
} catch (IOException ex) {
Logger.getLogger(SecondFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(f);
secondField.setText(f);
}
}
现在问题是我无法在setTo()函数中获取textField的值,因此返回null。 注意:两个FXML文件都应该在同一阶段加载
任何人都可以提供解决方案
答案 0 :(得分:0)
我建议返回StringProperty
,而不是从方法返回String。稍后您可以将此String属性绑定到Label的textProperty
。
public class FXMLDocumentController implements Initializable {
...
@FXML
private TextField firstField;
...
public StringProperty firstFieldTextProperty() {
return firstField.textProperty();
}
...
}
在SecondFXMLController中,只需将secondLabel的textProperty绑定到该方法。
public class SecondFXMLController implements Initializable {
@FXML
private Label secondField;
...
@Override
public void initialize(URL url, ResourceBundle rb) {
...
FXMLLoader fxml = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
pane = fxml.load();
con = fxml.getController();
secondField.textProperty.bind(con.firstFieldTextProperty());
...
}
}