We develop a Java application under a Windows environment (OpenJDK17 for Windows), but recently it was requested to make sure everything works under MacOS. Even though it is a Java application, some things might happen and it did.
When I try to export a file, the file chooser being used (BasicFileChooser) works without problems under Windows and Ubuntu Linux, but the same action under MacOS, causes a class cast exception.
java.lang.ClassCastException: class com.apple.laf.AquaFileChooserUI cannot be cast to class javax.swing.plaf.basic.BasicFileChooserUI (com.apple.laf.AquaFileChooserUI and javax.swing.plaf.basic.BasicFileChooserUI are in module java.desktop of loader 'bootstrap')
You might be thinking why don't I just use JFileChooser, but unfortunately I need to be able to get the GUI and update the name of the file in the text field on the fly.
For that, I have the following code:
//fileName is global variable here...
Utilities.invokeLater(() -> ((BasicFileChooserUI) getUI()).setFileName(fileName));
So you see, I need the "getUI()" from the FileChooser so I can have access to the "setFileName" method.
Any simple workaround would be enough. I wanted this:
if (fileName != null && !fileName.isEmpty()) {
val osType = doPrivileged(getOSTypeAction());
if (osType == WINDOWS || osType == LINUX) {
invokeLater(() -> ((BasicFileChooserUI) getUI()).setFileName(fileName));
}
if (osType == MACOSX) {
invokeLater(() -> ((AquaFileChooserUI) getUI()).setFileName(fileName));
}
}
But I can't call "AquaFileChooserUI" from a Windows JDK.
Any suggestions?
You can use reflection, assuming the method is named the same on all platforms: