javaFX在一个按钮的事件中显示另一个窗体

懵懂的女人 提交于 2020-02-26 11:44:15

第一个窗体的按钮事件:

 @FXML
    protected  void show2Action() throws IOException {
        Stage stage = new Stage();
        AnchorPane pane = FXMLLoader.load(getClass().getResource("javafxcontroller2.fxml"));
        Scene scene = new Scene(pane,300,400);
        stage.setScene(scene);
        stage.show();
    }

代码很简单,第二个窗体的fxml文件:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<AnchorPane fx:id="containerid" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.javafxminademo.Javafxcontroller2">
   <children>
      <GridPane layoutX="149.0" layoutY="116.0">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Label id="lblinfo" fx:id="lblinfo" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="1" />
            <Button fx:id="btnid" mnemonicParsing="false" text="Button" GridPane.rowIndex="2" />
         </children>
      </GridPane>
   </children>
</AnchorPane>

但是程序始终说FXMLLoader.load空指针异常,很明显就是getClass().getResource不正确,经过仔细查看,发现是我的第一个controller所在的类与第二controller所在类的路径不一样,所以将getResource时的路径应该以第二个controller相对于第一个controller的类路径作为参数,改为:

AnchorPane pane = FXMLLoader.load(getClass().getResource("../javafxcontroller2.fxml"));

则一切都正常了。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!