所以,我正在尝试在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场景生成器中设计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
}
}
答案 0 :(得分:1)
您发布的错误表示代码正在尝试将按钮加载为锚点窗格。检查你是否有一个带有fx的锚板:我是button1。