You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code中不借助项目管理器运行带FXML的JavaFX应用失败及配置问题求助

VS Code中不借助项目管理器运行带FXML的JavaFX应用失败及配置问题求助

我遇到了一个JavaFX应用的运行问题,具体情况如下:

问题场景1:Maven项目中带FXML的JavaFX应用无法通过VS Code默认调试配置(F5)启动

这个项目本身没问题,用mvn exec:java命令可以正常运行,但按下F5用.json配置启动就失败了。不过不带FXML的简单JavaFX应用用同样的.json配置却能正常运行。

主类代码

public class MediaAppPlayer extends Application {
  @Override
  public void start(Stage stage) {
    try {
      System.out.println("im here ....................");
      // Load the FXMLL file
      FXMLLoader loader =
          new FXMLLoader(getClass().getResource("/MediaPlayer.fxml"));
      Parent root = loader.load();

      // Set up the scene
      Scene scene = new Scene(root, 500, 200);

      // Bind the MediaView size to the scene size
      Controller controller = loader.getController();
      controller.bindMediaViewSize(scene);
      controller.bindHBoxSize(scene);

      // Set up the stage
      stage.setTitle("Media Player");
      stage.setScene(scene);
      stage.show();

      System.out.println("FXML file loaded sucessfully ....................");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

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

VS Code调试配置(launch.json)

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "Current File",
            "request": "launch",
            "mainClass": "${file}",
            // create java run time component
            "vmArgs": "--module-path \"C:/apps/javafx-sdk-21.0.5/lib\" --add-modules javafx.controls,javafx.fxml"
        }
    ]
}

MediaPlayer.fxml文件

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.media.MediaView?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.VBox?>

<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="demo.Controller">
    <center>
        <VBox alignment = "CENTER">
            <MediaView fx:id="mediaView" />
            <Slider fx:id="seekSlider" min="0" max="100" />
        </VBox>
    </center>
    <bottom>
        <HBox fx:id="hBox" spacing="10">
            <Button text="Open File" onAction="#handleOpenFile" />
            <Button text="Play" onAction="#handlePlay" />
            <Button text="Pause" onAction="#handlePause" />
            <Button text="Stop" onAction="#handleStop" />
            <ImageView fitWidth="20" preserveRatio="true">
                <image>
                    <Image url="@icons/volumeicon.png" />
                </image>
            </ImageView>
            <Slider fx:id="volumeSlider" min="0" max="100" />
            <Label fx:id="currentTimeLabel" text="00:00" />
            <Label fx:id="totalTimeLabel" text="00:00" />
        </HBox>
    </bottom>
</BorderPane>

Controller类代码

public class Controller {

    @FXML
    private MediaView mediaView;
    @FXML
    private Slider volumeSlider;
    @FXML
    private Slider seekSlider;
    @FXML
    private Label currentTimeLabel;
    @FXML
    private Label totalTimeLabel;
    @FXML
    private HBox hBox;

    private MediaManager mediaManager;

    @FXML
    public void initialize() {
        hBox.setPadding(new Insets(0,0,10,0));
        mediaManager = new MediaManager(mediaView, volumeSlider, seekSlider, currentTimeLabel, totalTimeLabel);
    }
    public void bindMediaViewSize(Scene scene) {
        // Bind the MediaView size to the scene size
        mediaView.fitWidthProperty().bind(scene.widthProperty());
        mediaView.fitHeightProperty().bind(scene.heightProperty().subtract(60)); // Adjust height to account for controls

        // Preserve the aspect ratio of the media
        mediaView.setPreserveRatio(true);
    }

    // create a method to Bind the HBox and seeker slider size to the scene size
    public void bindHBoxSize(Scene scene) {
        // Bind the HBox and seeker slider size to the scene size
        hBox.prefWidthProperty().bind(scene.widthProperty());
        seekSlider.prefWidthProperty().bind(scene.widthProperty());
    } 

    @FXML
    private void handlePlay() {
        mediaManager.play();
    }

    @FXML
    private void handlePause() {
        mediaManager.pause();
    }

    @FXML
    private void handleStop() {
        mediaManager.stop();
    }

    @FXML
    private void handleOpenFile() {
        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(null);
        if (file != null) {
            mediaManager.loadMedia(file);
        }
    }
}

pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>demo</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>21</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>21</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-media</artifactId>
            <version>21</version>
        </dependency>
    </dependencies>

<build>
    <plugins>
        <!-- Maven Compiler Plugin. here source and target has same java version to fix compatibility while build the project -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>21</source>
                <target>21</target>
            </configuration>
        </plugin>
        <!-- Maven Exec Plugin -->
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>demo.MediaAppPlayer</mainClass>
                
            </configuration>
        </plugin>
        
    </plugins>
</build>
</project>

错误信息

C:\Users\Kiran\OneDrive\Documents\VS Code\Media_Player\demo> cmd /C ""C:\Program Files\Java\jdk-21\bin\java.exe" -agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:55228 
@C:\Users\Kiran\AppData\Local\Temp\cp_4l8owl80fisy30v5w8p9jmqto.argfile demo.MediaAppPlayer "
im here ....................
Exception in Application start method
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:118)
        at java.base/java.lang.reflect.Method.invoke(Method.java:580)
        at javafx.graphics@21.0.5/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
        at javafx.graphics@21.0.5/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)        
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
        at java.base/java.lang.reflect.Method.invoke(Method.java:580)
        at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1135)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at javafx.graphics@21.0.5/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:893)
        at javafx.graphics@21.0.5/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
        at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x3a6815b) 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 @0x3a6815b
        at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
        at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2143)
        at demo.MediaAppPlayer.start(MediaAppPlayer.java:19)
        at javafx.graphics@21.0.5/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:839)
        at javafx.graphics@21.0.5/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:483)
        at javafx.graphics@21.0.5/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:456)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
        at javafx.graphics@21.0.5/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:455)
        at javafx.graphics@21.0.5/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at javafx.graphics@21.0.5/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics@21.0.5/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:185)
        ... 1 more
Exception running application demo.MediaAppPlayer

已尝试的操作

场景1:Maven项目中

  • 已通过Maven添加正确的JavaFX依赖
  • 确认了JDK和JavaFX版本(都是21)的兼容性
  • 在launch.json中配置了正确的VM参数和主类

场景2:手动创建非项目管理器的JavaFX项目(不带FXML可运行,带FXML不行)

  • 创建了lib、src、bin文件夹
  • 将JavaFX的jar包放入lib目录
  • 配置了指向lib目录的VM参数
  • 尝试添加了类路径到launch.json(不确定是否正确)

我的疑问

  1. 为什么带FXML的JavaFX应用用launch.json调试启动失败,但不带FXML的却可以?
  2. 如何在VS Code中手动运行带FXML的JavaFX应用(不借助Maven等项目管理器)?

备注:内容来源于stack exchange,提问作者Aero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 11:18:11