我正在尝试使用Scene Builder在JavaFX中创建一个按钮,但是出现了一些问题。这是我的代码:
MainDesign.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MainDesign extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("application/Design.fxml"));
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
DesignController.java:-
package application;
import java.awt.Button;
import javafx.fxml.FXML;
public class DesignController {
@FXML private Button b1;
}
Design.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.DesignController">
<center>
<Button fx:id="b1" mnemonicParsing="false" text="Button" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
错误:
Exception in Application start method
java.lang.reflect.InvocationTargetException
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x22e6b9c) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x22e6b9c
Exception running application application.MainDesign
因此,它正在MainDesign.java
文件中生成异常,我想这与FXML加载程序有关。
如果有人有解决此类问题的方法,请帮助我!!!
答案 0 :(得分:1)
Button
组件令人困惑;在 Design.fxml 中,您正在使用javafx.scene.control.Button
;在 DesignController.java 中,您正在使用java.awt.Button
。 JavaFX和Java AWT是独立的库,因此当FXML加载器读取此行时,它引起了一个问题:
@FXML private Button b1;
因为它无法在FXML文件中的b1
与控制器中的b1
之间建立连接。您必须在控制器中导入javafx.scene.control.Button
。