我试图从一个控制器传递一个值是另一个。我正在将第二个控制器加载到第一个控制器并运行第二个控制器中的setLabelViewPassed()方法。我遇到的问题是,当我使用getLabelViewPassed方法时,它不会收到传递的值。我计算出传递的值,当我运行它时,值显示出来,所以我不会'知道出了什么问题。
Controller One
package sample.controllers;
import com.jfoenix.controls.JFXButton;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerOne {
private String passedValue;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label labelViewOne;
@FXML
private JFXButton viewOneButton;
@FXML
void initialize() {
viewOneButton.setOnAction(event -> {
passedValue = labelViewOne.getText();
showControllerViewTwo();
});
}
public void showControllerViewTwo() {
//Get the current scene and hide it
viewOneButton.getScene().getWindow().hide();
//Get new view in FXML loader
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample/views/controllerTwo.fxml"));
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
ControllerTwo controllerTwo = loader.getController();
controllerTwo.setLabelViewPassed(passedValue);
Parent root = loader.getRoot();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.showAndWait();
}
}
控制器二
package sample.controllers;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerTwo {
private String labelViewPassed;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Label labelViewTwo;
@FXML
private JFXButton viewTwoButton;
@FXML
private JFXTextField textFieldViewTwo;
@FXML
void initialize() {
textFieldViewTwo.setText(getLabelViewPassed());
viewTwoButton.setOnAction(event -> {
});
}
public String getLabelViewPassed() {
return labelViewPassed;
}
public void setLabelViewPassed(String labelViewPassed) {
this.labelViewPassed = labelViewPassed;
System.out.println(labelViewPassed);
}
}
我知道这很简单,但出于某种原因,即使在搜索之后我也无法弄明白。我只是试图从控制器1中的标签传递值来设置控制器2中标签的文本。
打印出传递给第二个控制器的值,但标签不显示此新值。
答案 0 :(得分:1)
initialize()
执行期间调用 FXMLLoader.load()
(因此在调用setLabelViewPassed(...)
之前称为)。
将设置标签文本的行移动到setLabelViewPassed()
方法:
@FXML
void initialize() {
viewTwoButton.setOnAction(event -> {
});
}
public String getLabelViewPassed() {
return labelViewPassed;
}
public void setLabelViewPassed(String labelViewPassed) {
this.labelViewPassed = labelViewPassed;
textFieldViewTwo.setText(labelViewPassed);
System.out.println(labelViewPassed);
}