[英]want to change label text from another fxml controller class in javafx
[英]JavaFX and FXML - update label with data from another controller
我有一個帶有標簽和按鈕的窗口,另一個帶有 TextField 和按鈕的窗口。 在主窗口中,我想使用按鈕打開另一個窗口,在新窗口的文本字段中輸入一些內容,單擊新窗口上的按鈕后,我希望它關閉,主窗口標簽用文本更新那是輸入。 另外我希望新窗口是模態的。
public class MainController {
@FXML
public void showNewWindow() {
try {
Stage newWindowStage = new Stage();
newWindowStage.setTitle("New Window");
newWindowStage.initModality(Modality.APPLICATION_MODAL);
VBox root = FXMLLoader.load(getClass().getResource("newWindow.fxml"));
Scene scene = new Scene(root);
newWindowStage.setScene(scene);
newWindowStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class NewWindowController {
@FXML
private TextField textField;
@FXML
public void updateMainWindowLabel() {
// update label in main window
// close new window
}
}
我知道它根本沒有設置正確,但希望它解釋了我正在嘗試做的事情。
你需要 2 個階段來做你想做的事情(不僅僅是 2 個場景)。
Stage st
st.setOnCloseRequest(e -> {
});
將允許在您的舞台關閉時執行您想要的任何代碼(您的新窗口)。
然后在 TextField 對象上使用getText()
- 並在主舞台 Label 對象上使用setText()
。
st.initModality(Modality.APPLICATION_MODAL);
...將使其成為模態。
這是有效的示例代碼(它不是最簡潔的,所以我很感激編輯)
我對模態窗口沒有完全了解,但在這里我發現了另一個與此相關的問題。
擴展應用程序的主類:
public static void main(String[] args) {
Application.launch(Test.class, args);
}
private static Stage stage1;
private static Stage stage2;
private static MyExampleController controller;
@Override
public void start(Stage primaryStage) throws Exception {
stage1 = primaryStage;
FXMLLoader loader1 = new FXMLLoader(Test.class.getResource("/test/MyExample.fxml"));
AnchorPane pane1 = (AnchorPane)loader1.load();
controller = loader1.getController();
Scene scene1 = new Scene(pane1);
stage1.setScene(scene1);
stage2 = new Stage();
FXMLLoader loader2 = new FXMLLoader(Test.class.getResource("/test/MyEx2.fxml"));
AnchorPane pane2 = (AnchorPane)loader2.load();
Scene scene2 = new Scene(pane2);
stage2.setScene(scene2);
stage1.show();
}
public static Stage getStage2(){
return stage2;
}
public static MyExampleController getController(){
return controller;
}
控制器類 1:
public class MyExampleController implements Initializable {
@FXML
private Label labLab;
@FXML
private Button btnButton;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void clickButton(ActionEvent event) {
Test.getStage2().show();
}
public void updateLabel(String newLabelText){
this.labLab.setText(newLabelText);
}
}
控制器類 2:
public class MyEx2Controller implements Initializable {
@FXML
private Button btnUpdate;
@FXML
private TextField txtField;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void doUpdateForTitle(ActionEvent event) {
Test.getController().updateLabel(txtField.getText());
Test.getStage2().close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.