Sample Groovy / Java File Chooser

Here is a quick bit f code to choose a single file or directory. It’s written in groovy but uses java’s JFileChooser. It has many more options than demonstrated here, Look at the oracle link here.

// groovy sample to choose one file using java's  JFileChooser
// would only allow choice of a single directory by setting another JFileChooser feature
// see more examples in above link to include a file filter
import javax.swing.JFileChooser;
// start to choose files from pwd
def initialPath = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser(initialPath);
// fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog( null );
switch ( result )
   case JFileChooser.APPROVE_OPTION:
      File file = fc.getSelectedFile();

      def path =  fc.getCurrentDirectory().getAbsolutePath();
      println "path="+path+"\nfile name="+file.toString();
   case JFileChooser.CANCEL_OPTION:
   case JFileChooser.ERROR_OPTION:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s