Use a Swing File Chooser if JUI needs the user to pick a file

This commit is contained in:
Syer10
2021-05-03 16:03:12 -04:00
parent 177a872161
commit 7241fe6980

View File

@@ -10,6 +10,8 @@ import ca.gosyer.BuildConfig
import net.harawata.appdirs.AppDirs
import net.harawata.appdirs.AppDirsFactory
import java.io.File
import javax.swing.JFileChooser
import javax.swing.SwingUtilities
val appDirs: AppDirs by lazy {
AppDirsFactory.getInstance()
@@ -20,3 +22,34 @@ val userDataDir: File by lazy {
if (!it.exists()) it.mkdirs()
}
}
/**
* Opens a swing file picker, in the details view by default
*
* @param builder invokes this builder before launching the file picker, such as adding a action listener
* @param onCancel the listener that is called when picking a file is canceled
* @param onError the listener that is called when picking a file exited with a error
* @param onApprove the listener that is called when picking a file is completed
*/
fun filePicker(
builder: JFileChooser.() -> Unit = {},
onCancel: (JFileChooser) -> Unit = {},
onError: (JFileChooser) -> Unit = {},
onApprove: (JFileChooser) -> Unit
) = SwingUtilities.invokeLater {
val fileChooser = JFileChooser()
.apply {
val details = actionMap.get("viewTypeDetails")
details?.actionPerformed(null)
}
.apply(builder)
val result = fileChooser
.showOpenDialog(null)
when (result) {
JFileChooser.APPROVE_OPTION -> onApprove(fileChooser)
JFileChooser.CANCEL_OPTION -> onCancel(fileChooser)
JFileChooser.ERROR_OPTION -> onError(fileChooser)
}
}