mavenswingjavafxjfilechooser

How do I import a Java Swing package to a JavaFXML Maven project?


I am making a first attempt in developing a small desktop application using Netbeans, Maven and JavaFXML. I have chosen to use a previous version of an application that was developed using Ant and get this working in Maven. However in one of my java classes the Maven version is flagging an import of javax.swing.filechooser.FileSystemView as

package javax.swing.filechooser is not visible. Package javax.swing.filechooser is declared in module java.desktop but module myapp does not read it. 

This issue did not occur in the previous version. I have searched this forum, the Oracle forum and many web searches for a solution without success. I would appreciate some help in solving the issue.

I have searched this forum, the Oracle forum and many web searches for a solution without success. I was hoping to find an answer like 'download the swing API from here' but there appears no way of doing this. Anyway, the project properties for Maven do not have a ClassPath option for importing libraries. I would appreciate some help in solving the issue as to be honest I don't have a clue how to do this myself.


Solution

  • Require the needed module

    You probably need this line in your module-info.java:

    requires java.desktop;
    

    Explanation

    java.desktop is the module in which the Swing classes reside. A modular project needs to require access to it to be able to use it. Non-modular projects don't need to do that, because they read everything from the classpath and have no modularity. All old Java applications were non-modular because modules were only introduced with Java 9.

    Swing at Java 23, is still part of the standard JDK and runtime. All of its code was moved into the java.desktop module and is available in the base java runtime image. So you don't need to download the java.desktop module dependencies for Swing externally and add them to the module path as you do with most JavaFX distributions.

    Recommendation: Avoid mixing Swing and JavaFX code

    While the requirement of the java.desktop module will likely fix your immediate module access issue, I recommend against it. It is better to refactor your code to not use Swing (or AWT). Use JavaFX alone. Mixing JavaFX and Swing is possible, but there are numerous pitfalls in trying to do that, so I don't recommend it if it can be avoided.

    As noted in comments by @Abra, JavaFX has a FileChooser component. Its operation and API are different from the old Swing FileSystemView that you are using, but would likely be a good candidate replacement for you after some refactoring of your code.