【问题标题】:Switching scenes in JavaFX(FXML) error在 JavaFX(FXML) 错误中切换场景
【发布时间】:2017-10-13 14:03:58
【问题描述】:

所以,我正在尝试在 JavaFX 中切换场景,但是当我对其进行硬编码时,我似乎无法让它工作,我能够通过使用 lambda 表达式让它工作。

public class Main extends Application {

Stage window;
Scene scene1;
Scene scene2;

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    window = primaryStage;

    Label label = new Label("Welcome to the first scene");
    Button bttn1 = new Button("Go to second scene");
    bttn1.setOnAction(e -> window.setScene(scene2));

    //Scene 1
    VBox layout1 = new VBox(20);
    layout1.getChildren().addAll(label, bttn1);
    scene1 = new Scene(layout1, 400, 400);

    //Scene 2
    Button bttn2 = new Button("Go to first scene");
    bttn2.setOnAction(e -> window.setScene(scene1));

    StackPane layout2 = new StackPane();
    layout2.getChildren().add(bttn2);
    scene2 = new Scene(layout2, 400, 500);

    window.setScene(scene1);
    window.setTitle("Test");
    window.show();
}

但是该项目涉及几个不同的 GUI,我更愿意在 FXML Scene Builder 中设计 GUI,而不是使用 FX 方式对其进行硬编码。但是,当我尝试使用 FXML 方式时,它没有工作,当我按下按钮时总是出现错误。

错误信息

这是文档控制器代码。

public class FXMLDocumentController implements Initializable {

@FXML
private Button button1;

@FXML
private Button button2;

@FXML
private void handleButtonAction(ActionEvent event) throws IOException {
    Stage stage;
    Parent root;

   if(event.getSource() == button1){
       stage=(Stage)button1.getScene().getWindow();

       root = FXMLLoader.load(getClass().getResource("FXML2.fxml"));
   }
   else{
       stage=(Stage)button2.getScene().getWindow();
       root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
   }
   Scene scene = new Scene(root);
   stage.setScene(scene);
   stage.show();

}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}    

}

【问题讨论】:

  • 在您的帖子中,Initializable {public class Main extends Application { 未格式化为代码。
  • 抱歉,我现在就解决这个问题。感谢现场。

标签: javafx


【解决方案1】:

您发布的错误表明代码正在尝试将按钮加载为锚窗格。检查您是否有一个带有 fx:I'd of button1 的锚窗格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 2016-04-13
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多