Open a new scene(has its own controller) from anot

2019-12-16 19:50发布

I'm new to JavaFX and still learning I have this problem and couldn't find an answer.

I have two FXML files named "one.fxml" and "two.fxml" and they have their own controller classes naming "OneController.java" and "TwoController.java"

I'm want to open a "two.fxml" with onButtonClick from "one.fxml".

The Button Code in "one.fxml" is:

<Button fx:id="clearButton" layoutX="690.0" layoutY="309.0" minHeight="18.0" mnemonicParsing="false" prefHeight="40.0" prefWidth="196.0" text="Clear" onAction="#buttonclearClick"/>

and I have this method in "OneController.java"

private void buttonclearClick(final ActionEvent event)
{
  //code to be written?
}

also how do I transfer values of the certain fields from "one.fxml" to "two.fxml"

like:

if "one.fxml" also has this tag:

<Text fx:id="textLabel" fill="#001f4b" layoutX="14.0" layoutY="377.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Powered by StackOverflow">

how do I transfer this text field value(text="Powered by StackOverflow") to "two.fxml" or TwoController.java

How to achieve this?

1条回答
Rolldiameter
2楼-- · 2019-12-16 20:34

One Controller

            private void buttonclearClick(final ActionEvent event)
            {
              try
              {

                FXMLLoader loader = new FXMLLoader(getClass().getResource("two.fxml"));
                Stage stage = new Stage();
                stage.initModality(Modality.APPLICATION_MODAL);
                //stage.initOwner(MainStage.stage);
                stage.setScene(new Scene((Pane)loader.load()));
                TwoController tsc = loader.<TwoController>getController();
                tsc.GettextVal(textLabel.getText()); // Function in TwoController
                stage.show();

              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
            }

Two Controller

Make a function GettextVal in two controller

          @FXML
          void initialize() 
          {
             //Initialize code here
          }

          public void GettextVal(String txtval)
          {
             System.out.println("text value from one controller - "+txtval);
          }
查看更多
登录 后发表回答