我已经反复搜索过这个问题,但没有结果。我有一个连接到 Controller 的 JavaFX FXML 窗口;这个窗口是打开的。单击窗口上的按钮会触发另一个 FXML 文件的打开,该文件链接到其各自的 Controller 。
第二个窗口(optionsUI.fxml 和 optionsController)有一些单选按钮。单击其中一个时,我希望在 mainUI 窗口中更改图像/按钮的位置。我该如何去做呢?
主 Controller :
public void assetPressed(MouseEvent event) {
//Get the source of Handler
HUDButton button = (HUDButton) event.getSource();
//Check if an asset is already selected
//----do a thing
//Open stage
openStage(currentAsset);
} else {
//if the current asset selected and the new asset clicked are the same
//----do something
closeStage();
}
//if the current asset selected and the new asset clicked are different
else {
//----do something else
assetIsSelected = true;
openStage(currentAsset);
}
}
}
//opening optionsUI.fxml
public void openStage(Asset asset) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("optionsUI.fxml"));
Parent root = null;
try {
root = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
optionsController controller = fxmlLoader.getController();
Scene scene = new Scene(root, 300, 450);
stage.setScene(scene);
if (alreadyExecuted == false) {
stage.initStyle(StageStyle.UNDECORATED);
stage.initOwner(stageControls); //Making the mainUI the owner of the optionsUI
stage.setTitle("HUDEdit Version 3.0.0");
alreadyExecuted = true;
}
我遇到的主要问题是在单选按钮上添加一个事件处理程序,这将更改按下的按钮(currentButton)的属性。我搜索了这个问题,但我得到的是我已经做过的事情:使用其他 FXML 文件中存在的新值打开一个新阶段。
最佳答案
您可以在 OptionsController
中执行类似的操作(顺便说一句,我将重命名内容以符合标准 naming conventions 。)
这里的基本思想只是公开一个表示用户通过单选按钮选择的内容的属性。
public class OptionsController {
@FXML
private RadioButton radioButton1 ;
@FXML
private RadioButton radioButton2 ;
private SomeType someValue1 = new SomeType();
private SomeType someValue2 = new SomeType();
private final ReadOnlyObjectWrapper<SomeType> selectedThing = new ReadOnlyObjectWrapper<>();
public ReadOnlyObjectProperty<SomeType> selectedThingProperty() {
return selectedThing.getReadOnlyProperty() ;
}
public final SomeType getSelectedThing() {
return selectedThingProperty().get();
}
public void initialize() {
radioButton1.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedThing.set(someValue1);
}
});
radioButton2.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedThing.set(someValue2);
}
});
}
// ...
}
现在,当您加载 Options.fxml
时,您可以观察该属性,并在其值发生变化时执行您需要的操作:
public void openStage(Asset asset) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("optionsUI.fxml"));
Parent root = null;
try {
root = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
OptionsController controller = fxmlLoader.getController();
controller.selectedThingProperty().addListener((obs, oldSelection, newSelection) -> {
// do whatever you need with newSelection....
});
// etc...
}
关于java - 与已打开的 FXML Controller 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669592/