Re: Changing the default file filter in
geertjan wielenga <[email protected]>
| Newsgroups | gmane.comp.java.netbeans.modules.openide.devel |
|---|---|
| Organization | Oracle Corporation |
| Message-ID | <[email protected]> |
Hi Matvei,
This may be the only way to do that, I think.
Gj
On 13-7-2016 22:10, matvei.stefarov wrote:
> I am creating a NetBeans-Platform-based "viewer" application that supports several custom file formats. I'm wondering if it's possible to change the default "Open File..." dialog to select a filter other than "All Files" by default.
>
> Here is the code that builds the FileChooser: http://hg.netbeans.org/main/file/c7b8745b5c39/utilities/src/org/netbeans/modules/openfile/OpenFileAction.java#l103
>
> I found a workaround that sets OpenFileAction.currentFileFilter field via reflection, but it feels very fragile and hacky:
>
>
> Code:
> import java.lang.reflect.Field;
> import java.util.Arrays;
> import javax.swing.filechooser.FileFilter;
> import org.openide.filesystems.*;
> import org.openide.modules.ModuleInstall;
> import org.openide.util.Exceptions;
> import org.openide.util.Lookup;
>
> public class Installer extends ModuleInstall {
>
> @Override
> public void restored() {
> // Sets the default file filter of "Open File" dialog to "PDF Documents", instead of "All Files"
> try {
> // Find the description of the FileFilter generated for PdfDataObject
> FileChooserBuilder fcb = new FileChooserBuilder(Installer.class);
> fcb.addDefaultFileFilters();
> FileFilter filter = Arrays.stream(fcb.createFileChooser().getChoosableFileFilters())
> .filter(f -> f.getDescription().contains("pdf"))
> .findFirst()
> .get();
> String pdfFilterDescription = filter.getDescription();
>
> // Set the currentFileFilter field of the OpenFileAction class
> ClassLoader gcl = Lookup.getDefault().lookup(ClassLoader.class);
> Class<?> ofaClass = gcl.loadClass("org.netbeans.modules.openfile.OpenFileAction");
> Field cffField = ofaClass.getDeclaredField("currentFileFilter");
> cffField.setAccessible(true);
> cffField.set(null, pdfFilterDescription);
>
> } catch (Exception ex) {
> Exceptions.printStackTrace(ex);
> }
> }
> }
>
>
>
>
> Unfortunately I cannot find any sensible way to extend OpenFileAction without reflection. Can anyone think of a better way to accomplish this behavior?
>
>
>
>