通过另一个控制器更改comboBox的值不会触发JavaFX中的onAction回调

时间:2019-04-02 06:33:48

标签: javafx fxml

那里有两个控制器及其各自的FXML文件。 如果单击 View1.fxml 中的button,则更改了comboBox的值,但是未在控制台中获得输出。 但是,如果我单击 View2.fxml 中的changeValueOfDemoComboBoxBtn,则输出将打印在控制台中。

View1.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller1">
   <children>
      <Button fx:id="button" layoutX="187.0" layoutY="120.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Button" />
   </children>
</AnchorPane>

View2.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller2">
   <children>
      <Button fx:id="changeValueOfDemoComboBoxBtn" layoutX="200.0" layoutY="264.0" mnemonicParsing="false" onAction="#handleChangeValueOfDemoComboBoxBtnAction" text="Button" />
      <ComboBox fx:id="demoComboBox" layoutX="161.0" layoutY="127.0" onAction="#handleDemoComboBox" prefWidth="150.0" />
   </children>
</AnchorPane>

Controller1.java

@FXML
private Button button;

@FXML
private void handleButtonAction() throws IOException {

        StackPane contentStackPane = (StackPane)mainScene.lookup("#contentStackPane");

        FXMLLoader loader = new FXMLLoader(getClass().getResource("view2.fxml));
        Parent view2Fxml = loader.load();

        Controller2 controller2 = loader.getController();

        controller2.setDemoComboBox("Apple");

        contentStackPane.getChildren().removeAll();
        contentStackPane.getChildren().setAll(view2Fxml );
}

Controller2.java

@FXML
private ComboBox<String> demoComboBox;

@FXML
private Button changeValueOfDemoComboBoxBtn;

@FXML
private void handleDemoComboBox() {

        System.out.println("Value changed in Demo ComboBox");
}

@FXML
private void handleChangeValueOfDemoComboBoxBtnAction(){

        setDemoComboBox("Oranges");
}

public void setDemoComboBox(String value){

        demoComboBox.setValue(value);
}


0 个答案:

没有答案