Monday, December 11, 2017

JAVAFX - How select file (FileChooser)

Typical open file dialog:
/* - select file */

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle( "Select image.." );
    
/* - get saved directory - or get user`s home dir */

File pDir = new File( app.pSetup.getData().sLastPath );
if ( ! ( pDir.exists() && pDir.isDirectory() ) ) {      
  pDir = new File( System.getProperty( "user.home" ) );      
}  
 fileChooser.setInitialDirectory( pDir );
    
/* - set filters */
    
fileChooser.getExtensionFilters().addAll(
  new FileChooser.ExtensionFilter( "All Images", "*.*" ),
  new FileChooser.ExtensionFilter( "JPG", "*.jpg" ),
  new FileChooser.ExtensionFilter( "PNG", "*.png" ),
  new FileChooser.ExtensionFilter( "BMP", "*.bmp" )
);
    
/* - open dialog */
    
File pfile = fileChooser.showOpenDialog( scrollPane.getScene().getWindow() );

/* - draw image */
    
if ( pfile != null )
{      
      
  /* -- read image */
      
  Image image = new Image( pfile.toURI().toURL().toExternalForm() );
  ...
}
Output:

No comments:

Post a Comment