groovyswingbuilder

Groovy Swing buider fileChooser


I am trying to use groovy swing builder's fileChooser with no luck. When I copy the following example from groovy website:

def openExcelDialog  = SwingBuilder.fileChooser(dialogTitle:"Choose an excel file", 
                               id:"openExcelDialog", fileSelectionMode :         JFileChooser.FILES_ONLY, 
                               //the file filter must show also directories, in order to be able to look into them
                               fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter) {

}

But I got an error message:

groovy.lang.MissingMethodException: No signature of method: static groovy.swing.SwingBuilder.fileChooser() is applicable for argument types: (java.util.LinkedHashMap, ConsoleScript19$_run_closure1) values

Solution

  • You can't use the fileChooser like that outside a SwingBuilder. Instead, you need to just use a normal, non-swingBuilder JFileChooser. Here's a complete working example:

    import javax.swing.filechooser.FileFilter
    import javax.swing.JFileChooser
    
    def openExcelDialog = new JFileChooser(
                                dialogTitle: "Choose an excel file",
                                fileSelectionMode: JFileChooser.FILES_ONLY, 
                                //the file filter must show also directories, in order to be able to look into them
                                fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter)
    
    openExcelDialog.showOpenDialog()
    

    Note that the new JFileChooser just ends with the closing parentheses - there's no trailing closure.