在JavaFX(FXML)中切换场景错误
所以,我试图在JavaFX中切换场景,但当我硬编码它时,我似乎无法让它工作。我能够通过使用lambda表达式使它工作在JavaFX(FXML)中切换场景错误,javafx,Javafx,所以,我试图在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 primaryStag
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
}
}
您发布的错误表示代码试图将按钮加载为锚窗格。检查一下你是否有一个带有fx:I'd按钮1的主播。在你的帖子中,
Initializable{
和public class Main extends应用程序{
没有被格式化为代码。很抱歉,我现在就解决这个问题。谢谢你的帮助。