Java examples for Swing:JComponent
Displays a Swing file selection dialog, and returns the URL of the image selected.
//package com.java2s; import java.net.*; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.io.File; public class Main { private static JFileChooser imageChooser = null; /**//from w ww.ja v a 2 s. c om * Displays a file selection dialog, and returns the URL of the image selected. * Files with extensions "jpg", "jpeg", "png", and "gif" are allowed. * This function is not thread safe. * @param parent parent component of the dialog, or null. * @param currentDirectory starting directory, or null for default. * @return the url of the selected image, null if the selection was cancelled or an error occurred. */ public static URL promptImageURL(Component parent, File currentDirectory) { if (imageChooser == null) { imageChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Images", "jpg", "jpeg", "png", "gif"); imageChooser.setFileFilter(filter); } if (currentDirectory != null) { imageChooser.setCurrentDirectory(currentDirectory); } URL result = null; int cValue = imageChooser.showOpenDialog(parent); if (cValue == JFileChooser.APPROVE_OPTION) { try { result = imageChooser.getSelectedFile().toURI().toURL(); } catch (Exception ex) { ex.printStackTrace(); } } return result; } }