下面列出了javax.swing.JFileChooser#getCurrentDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@inheritDoc} Displays a file chooser dialog and opens the selected
* files.
*/
@Override
public void actionPerformed(final ActionEvent e) {
if (running) {
return;
}
try {
running = true;
JFileChooser chooser = prepareFileChooser();
File[] files;
try {
files = chooseFilesToOpen(chooser);
currentDirectory = chooser.getCurrentDirectory();
} catch (UserCancelException ex) {
return;
}
for (int i = 0; i < files.length; i++) {
OpenFile.openFile(files[i], -1);
}
} finally {
running = false;
}
}
public void doLoad() {
JFileChooser fc = new JFileChooser(m_fCurrentDirectory);
fc.addChoosableFileFilter(new ExtensionsFilter(LocalRes.getIntString("label.imagefiles"), "png", "gif", "jpg", "jpeg", "bmp"));
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage img = ImageIO.read(fc.getSelectedFile());
if (img != null) {
// compruebo que no exceda el tamano maximo.
if (m_maxsize != null && (img.getHeight() > m_maxsize.height || img.getWidth() > m_maxsize.width)) {
if (JOptionPane.showConfirmDialog(this, LocalRes.getIntString("message.resizeimage"), LocalRes.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
// Redimensionamos la imagen para que se ajuste
img = resizeImage(img);
}
}
setImage(img);
m_fCurrentDirectory = fc.getCurrentDirectory();
}
} catch (IOException eIO) {
}
}
}
private File getSaveDirectory() {
JFileChooser fd = new JFileChooser();
fd.setCurrentDirectory(new File("."));
fd.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fd.setDialogTitle(Localizer.localize("SaveImagesToDirectoryTittle"));
fd.setAcceptAllFileFilterUsed(false);
if (fd.showOpenDialog(getRootPane().getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) {
File directory = fd.getCurrentDirectory();
File selectedFile = fd.getSelectedFile();
if ((selectedFile != null) && selectedFile.isDirectory()) {
return selectedFile;
} else if (directory != null) {
return directory;
}
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser choose = new JFileChooser(lastDir);
choose.showOpenDialog(null);
if (choose.getSelectedFile() != null) {
lastDir = choose.getCurrentDirectory();
BufferedImage im;
try {
im = ImageTools.read(choose.getSelectedFile());
GamePanelGUI.getInstance().getPanelBattleField().setBackgroundPicture(im);
GamePanelGUI.getInstance().getPanelBattleField().repaint();
MTGControler.getInstance().setProperty("/game/player-profil/background",choose.getSelectedFile().getAbsolutePath());
} catch (IOException e1) {
logger.error(e1);
}
}
}
public static String selectDirectory(Component component,String name,File pathToUse){
JFileChooser chooser = new JFileChooser();
boolean useIndicated = pathToUse != null;
if (useIndicated && lastIndicatedPath == null){
lastIndicatedPath = pathToUse;
}
chooser.setCurrentDirectory(useIndicated?lastIndicatedPath:lastChooserPath);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showDialog(component, name);
if ( result == JFileChooser.APPROVE_OPTION){
try{
if(useIndicated){
lastIndicatedPath = chooser.getCurrentDirectory();
}else{
lastChooserPath = chooser.getCurrentDirectory();
}
return chooser.getSelectedFile().getAbsolutePath();
}catch(Exception e){e.printStackTrace();}
}
return null;
}
private File snapshotFile() {
JFileChooser chooser = createFileChooser(lastDirectory);
Frame mainWindow = WindowManager.getDefault().getMainWindow();
if (chooser.showOpenDialog(mainWindow) == JFileChooser.APPROVE_OPTION) {
lastDirectory = chooser.getCurrentDirectory();
return chooser.getSelectedFile();
} else {
return null;
}
}
/**
* Query the user for a filename and save the plot to that file.
*/
protected void _saveAs() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.addChoosableFileFilter(new PLTOrXMLFileFilter());
fileDialog.setDialogTitle("Save plot as...");
if (_directory != null) {
fileDialog.setCurrentDirectory(_directory);
} else {
// The default on Windows is to open at user.home, which is
// typically an absurd directory inside the O/S installation.
// So we use the current directory instead.
String cwd = StringUtilities.getProperty("user.dir");
if (cwd != null) {
fileDialog.setCurrentDirectory(new File(cwd));
}
}
fileDialog.setSelectedFile(new File(fileDialog.getCurrentDirectory(), "plot.xml"));
int returnVal = fileDialog.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
_file = fileDialog.getSelectedFile();
setTitle(_file.getName());
_directory = fileDialog.getCurrentDirectory();
_save();
}
}
private void addFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFileButtonActionPerformed
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle(NbBundle.getMessage(SpringCustomizerPanel.class, "LBL_ChooseFile")); //NOI18N
chooser.setCurrentDirectory(basedir);
int option = chooser.showOpenDialog(SwingUtilities.getWindowAncestor(groupFilesList));
if (option == JFileChooser.APPROVE_OPTION) {
boolean showDialog = false;
List<File> newFiles = new LinkedList<File>();
StringBuilder existing = new StringBuilder(
NbBundle.getMessage(SpringCustomizerPanel.class, "LBL_FileAlreadyAdded")).append("\n"); //NOI18N
for (File file : chooser.getSelectedFiles()) {
if (files.contains(file)) {
existing.append(file.getAbsolutePath()).append("\n"); //NOI18N
showDialog = true;
} else {
newFiles.add(file);
}
}
// remember last location
basedir = chooser.getCurrentDirectory();
addFiles(newFiles);
if (showDialog) {
DialogDisplayer.getDefault().notify(
new NotifyDescriptor.Message(existing.toString(), NotifyDescriptor.ERROR_MESSAGE));
}
}
}
private void browseStylesheet(StylesheetComponent component) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(Language.I18N.getString("common.pref.xslt.label.file"));
FileNameExtensionFilter filter = new FileNameExtensionFilter("XSLT Stylesheet (*.xsl)", "xsl");
chooser.addChoosableFileFilter(filter);
chooser.addChoosableFileFilter(chooser.getAcceptAllFileFilter());
chooser.setFileFilter(filter);
File currentDirectory = null;
String stylesheet = component.stylesheet.getText().trim();
if (!stylesheet.isEmpty()) {
Path path = Paths.get(stylesheet).getParent();
if (path != null)
currentDirectory = path.toFile();
}
if (currentDirectory == null) {
if (lastPath != null)
currentDirectory = lastPath;
else
currentDirectory = ClientConstants.IMPEXP_HOME.resolve(ClientConstants.XSLT_TEMPLATES_DIR).toFile();
}
chooser.setCurrentDirectory(currentDirectory);
int result = chooser.showOpenDialog(getTopLevelAncestor());
if (result != JFileChooser.CANCEL_OPTION) {
component.stylesheet.setText(chooser.getSelectedFile().getAbsolutePath());
lastPath = chooser.getCurrentDirectory();
}
}
private void doFileSelectionModeChanged(PropertyChangeEvent e) {
doFilterChanged(e);
JFileChooser fc = getFileChooser();
File currentDirectory = fc.getCurrentDirectory();
if (currentDirectory != null && fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled()
&& fc.getFileSystemView().isFileSystem(currentDirectory)) {
setFileName(currentDirectory.getPath());
} else {
setFileName(null);
}
setFileSelected();
}
public static String selectFile(Component component, String name, String extension, File pathToUse){
JFileChooser chooser = new JFileChooser();
if(extension != null){
chooser.setFileFilter(new ExtensionFilter(extension));
}
boolean useGivenPath = pathToUse != null;
if (useGivenPath && lastIndicatedPath == null){
lastIndicatedPath = pathToUse;
}
chooser.setCurrentDirectory(useGivenPath?lastIndicatedPath:lastChooserPath);
int result = chooser.showDialog(component, name);
if ( result == JFileChooser.APPROVE_OPTION){
try{
if(useGivenPath){
lastIndicatedPath = chooser.getCurrentDirectory();
}else{
lastChooserPath = chooser.getCurrentDirectory();
}
String p = chooser.getSelectedFile().getAbsolutePath();
if (extension.startsWith(".")){
if (p.endsWith(extension)){
return p;
}else{
return p + extension;
}
}else{
if (p.endsWith(extension)){
return p;
}else{
return p + "." + extension;
}
}
}catch(Exception e){e.printStackTrace();}
}
return null;
}
public static String selectNonExistingFile(Component parent,String extensionWanted){
String forReturn = null;
final String endWith = extensionWanted;
JFileChooser chooser = new JFileChooser(lastChooserPath);
chooser.setFileFilter(new FileFilter(){
@Override
public boolean accept(File file) {
String filename = file.getName();
return (filename.endsWith(endWith)||file.isDirectory());
}
@Override
public String getDescription() {
return endWith;
}
});
int result = chooser.showSaveDialog(parent);
if ( result == JFileChooser.APPROVE_OPTION){
try{
lastChooserPath = chooser.getCurrentDirectory();
forReturn = chooser.getSelectedFile().getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
if(forReturn != null){
if(!forReturn.endsWith(extensionWanted)){
forReturn += extensionWanted;
}
}
return forReturn;
}
@Override
public void loggedActionPerformed(ActionEvent e) {
if (UIManager.getBoolean("FileChooser.readOnly")) {
return;
}
JFileChooser fc = getFileChooser();
File currentDirectory = fc.getCurrentDirectory();
FileSystemView fsv = fc.getFileSystemView();
File newFolder = null;
String name = SwingTools.showInputDialog("file_chooser.new_folder", "");
// abort if cancelled or user entered nothing
if (name == null || name.isEmpty()) {
return;
}
try {
newFolder = fsv.createNewFolder(currentDirectory);
if (newFolder.renameTo(fsv.createFileObject(fsv.getParentDirectory(newFolder), name))) {
newFolder = fsv.createFileObject(fsv.getParentDirectory(newFolder), name);
} else {
SwingTools.showVerySimpleErrorMessage("file_chooser.new_folder.rename", name);
}
} catch (IOException exc) {
SwingTools.showVerySimpleErrorMessage("file_chooser.new_folder.create", name);
return;
} catch (Exception exp) {
// do nothing
}
if (fc.isMultiSelectionEnabled()) {
fc.setSelectedFiles(new File[] { newFolder });
} else {
fc.setSelectedFile(newFolder);
}
fc.rescanCurrentDirectory();
}
private void addResource(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addResource
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
chooser.setAcceptAllFileFilterUsed(false);
if (this.volumeType.equals(PersistenceLibrarySupport.VOLUME_TYPE_CLASSPATH)) {
chooser.setMultiSelectionEnabled (true);
chooser.setDialogTitle(NbBundle.getMessage(J2SEVolumeCustomizer.class,"TXT_OpenClasses"));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter (new SimpleFileFilter(NbBundle.getMessage(
J2SEVolumeCustomizer.class,"TXT_Classpath"),new String[] {"ZIP","JAR"})); //NOI18N
chooser.setApproveButtonText(NbBundle.getMessage(J2SEVolumeCustomizer.class,"CTL_SelectCP"));
chooser.setApproveButtonMnemonic(NbBundle.getMessage(J2SEVolumeCustomizer.class,"MNE_SelectCP").charAt(0));
}
else if (this.volumeType.equals(PersistenceLibrarySupport.VOLUME_TYPE_JAVADOC)) {
chooser.setDialogTitle(NbBundle.getMessage(J2SEVolumeCustomizer.class,"TXT_OpenJavadoc"));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter (new SimpleFileFilter(NbBundle.getMessage(
J2SEVolumeCustomizer.class,"TXT_Javadoc"),new String[] {"ZIP","JAR"})); //NOI18N
chooser.setApproveButtonText(NbBundle.getMessage(J2SEVolumeCustomizer.class,"CTL_SelectJD"));
chooser.setApproveButtonMnemonic(NbBundle.getMessage(J2SEVolumeCustomizer.class,"MNE_SelectJD").charAt(0));
}
else if (this.volumeType.equals(PersistenceLibrarySupport.VOLUME_TYPE_SRC)) {
chooser.setDialogTitle(NbBundle.getMessage(J2SEVolumeCustomizer.class,"TXT_OpenSources"));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter (new SimpleFileFilter(NbBundle.getMessage(
J2SEVolumeCustomizer.class,"TXT_Sources"),new String[] {"ZIP","JAR"})); //NOI18N
chooser.setApproveButtonText(NbBundle.getMessage(J2SEVolumeCustomizer.class,"CTL_SelectSRC"));
chooser.setApproveButtonMnemonic(NbBundle.getMessage(J2SEVolumeCustomizer.class,"MNE_SelectSRC").charAt(0));
}
if (lastFolder != null) {
chooser.setCurrentDirectory (lastFolder);
}
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
lastFolder = chooser.getCurrentDirectory();
if (chooser.isMultiSelectionEnabled()) {
addFiles (chooser.getSelectedFiles());
}
else {
final File selectedFile = chooser.getSelectedFile();
addFiles (new File[] {selectedFile});
}
} catch (MalformedURLException mue) {
Exceptions.printStackTrace(mue);
}
}
}
protected void onCreateStoredObject()
{
List<StoredObject> sltObj = getSelectedStoredObjects() ;
if (sltObj != null && sltObj.size() > 1)
return ; // should never happen, because in such a case the menu is disable
StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ;
Container container = getSelectedContainer();
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setCurrentDirectory(lastFolder);
final JPanel optionPanel = getOptionPanel ();
chooser.setAccessory(optionPanel);
AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ;
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File[] selectedFiles = chooser.getSelectedFiles();
try
{
boolean overwriteAll = overwriteCheck.isSelected() ;
if (overwriteAll)
{
if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files")))
return ;
}
ops.uploadFiles(container, parentObject, selectedFiles, overwriteAll, getNewSwiftStopRequester (), callback);
// We open the progress window, for it is likely that this operation
// will take a while
//if (selectedFiles != null /*&& selectedFiles.length > 1*/)
//{
//onProgressButton () ;
//}
}
catch (IOException e)
{
logger.error("Error occurred while uploading a files.", e);
}
lastFolder = chooser.getCurrentDirectory();
}
}
private void doSaveSettings() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save as...");
chooser.setMultiSelectionEnabled(false);
chooser.setCurrentDirectory(workingDirectory);
int returnVal = chooser.showSaveDialog(Utils.getActiveFrame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
saveSettings(file);
File tmpDir = chooser.getCurrentDirectory();
if (tmpDir != null) {
workingDirectory = tmpDir;
}
setStatus("Saved as " + file.getAbsolutePath());
}// END: approve check
}
private void addJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addJarButtonActionPerformed
JFileChooser chooser = FileEditor.createHackedFileChooser();
chooser.setFileHidingEnabled(false);
setHelpToChooser( chooser );
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return (f.isDirectory() || f.getName().endsWith(".jar") || f.getName().endsWith(".zip")); // NOI18N
}
public String getDescription() {
return getString("CTL_JarArchivesMask");
}
});
if (lastJarFolder != null) {
chooser.setCurrentDirectory(lastJarFolder);
}
chooser.setDialogTitle(getString("CTL_FileSystemPanel.Jar_Dialog_Title"));
chooser.setMultiSelectionEnabled( true );
if (chooser.showDialog(this,
getString("CTL_Approve_Button_Title"))
== JFileChooser.APPROVE_OPTION) {
File[] files = chooser.getSelectedFiles();
boolean found = false;
for (int i=0; i<files.length; i++) {
if ((files[i] != null) && (files[i].isFile())) {
found = true;
String path = files[i].getAbsolutePath();
if (! listModel.contains (path)) {
listModel.addElement (path);
}
}
}
if ( found ) {
lastJarFolder = chooser.getCurrentDirectory();
fireValueChanged();
}
pathList.setSelectedIndex(listModel.size() - 1);
}
}
protected void onCompareDirectories ()
{
List<StoredObject> sltObj = getSelectedStoredObjects() ;
if (sltObj != null && sltObj.size() != 1)
return ; // should never happen, because in such a case the menu is disable
final StoredObject obj = sltObj.get(0) ;
if (!SwiftUtils.isDirectory(obj))
return ; // should never happen, because in such a case the menu is disable
final Container container = getSelectedContainer();
final JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(lastFolder);
//chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(false) ;
setDefaultFileChooserValue (chooser, obj) ;
chooser.setAcceptAllFileFilterUsed(false);
chooser.addChoosableFileFilter(getComparisonFileFilter(obj.getBareName(), true));
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
if (!checkFileNameIdentical (chooser.getSelectedFile().getName(), obj.getBareName()))
return ;
@SuppressWarnings("unchecked")
ResultCallback<Collection<Pair<? extends ComparisonItem, ? extends ComparisonItem> > > crcb = GuiTreadingUtils.guiThreadSafe(ResultCallback.class, new ResultCallback<Collection<Pair<? extends ComparisonItem, ? extends ComparisonItem> > > () {
@Override
public void onResult(Collection<Pair<? extends ComparisonItem, ? extends ComparisonItem> > discrepancies) {
showDifferencesManagementDlg (container, obj, chooser.getSelectedFile(), discrepancies, true) ;
}}) ;
try
{
ops.findDifferences(container, obj, chooser.getSelectedFile(), crcb, getNewSwiftStopRequester(), callback);
//onProgressButton();
}
catch (IOException e)
{
logger.error("Error occurred while comparing files.", e);
}
}
lastFolder = chooser.getCurrentDirectory();
}
SelectedFile selectSnapshotTargetFile(final String defaultName, final boolean heapdump) {
String targetName;
FileObject targetDir;
// 1. let the user choose file or directory
JFileChooser chooser = new JFileChooser();
if (exportDir != null) {
chooser.setCurrentDirectory(exportDir);
}
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle(Bundle.ResultsManager_SelectFileOrDirDialogCaption());
chooser.setApproveButtonText(Bundle.ResultsManager_SaveButtonName());
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.isDirectory() || f.getName().endsWith("." + (heapdump ? HEAPDUMP_EXTENSION : SNAPSHOT_EXTENSION)); //NOI18N
}
public String getDescription() {
if (heapdump) {
return Bundle.ResultsManager_ProfilerHeapdumpFileFilter(HEAPDUMP_EXTENSION);
}
return Bundle.ResultsManager_ProfilerSnapshotFileFilter(SNAPSHOT_EXTENSION);
}
});
if (chooser.showSaveDialog(WindowManager.getDefault().getMainWindow()) != JFileChooser.APPROVE_OPTION) {
return null; // cancelled by the user
}
// 2. process both cases and extract file name and extension to use
File file = chooser.getSelectedFile();
String targetExt = heapdump ? HEAPDUMP_EXTENSION : SNAPSHOT_EXTENSION;
if (file.isDirectory()) { // save to selected directory under default name
exportDir = chooser.getCurrentDirectory();
targetDir = FileUtil.toFileObject(FileUtil.normalizeFile(file));
targetName = defaultName;
} else { // save to selected file
exportDir = chooser.getCurrentDirectory();
targetDir = FileUtil.toFileObject(FileUtil.normalizeFile(exportDir));
String fName = file.getName();
// divide the file name into name and extension
int idx = fName.lastIndexOf('.'); // NOI18N
if (idx == -1) { // no extension
targetName = fName;
// extension will be used from source file
} else { // extension exists
if (heapdump || fName.endsWith("." + targetExt)) { // NOI18N
targetName = fName.substring(0, idx);
targetExt = fName.substring(idx + 1);
} else {
targetName = fName;
}
}
}
// 3. return a newly created FileObject
return new SelectedFile(targetDir, targetName, targetExt);
}
/**
* {@inheritDoc} Displays a file chooser dialog
* and opens the selected files.
*/
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
return;
}
try {
running = true;
JFileChooser chooser = prepareFileChooser();
File[] files;
try {
if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N
System.setProperty("apple.awt.fileDialogForDirectories", "false"); //NOI18N
FileDialog fileDialog = new FileDialog(WindowManager.getDefault().getMainWindow());
fileDialog.setMode(FileDialog.LOAD);
fileDialog.setDirectory(getCurrentDirectory().getAbsolutePath());
fileDialog.setTitle(chooser.getDialogTitle());
fileDialog.setVisible(true);
if( null != oldFileDialogProp ) {
System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N
} else {
System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N
}
if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) {
String selFile = fileDialog.getFile();
File dir = new File( fileDialog.getDirectory() );
files = new File[] { new File( dir, selFile ) };
currentDirectory = dir;
} else {
throw new UserCancelException();
}
} else {
files = chooseFilesToOpen(chooser);
currentDirectory = chooser.getCurrentDirectory();
if (chooser.getFileFilter() != null) { // #227187
currentFileFilter =
chooser.getFileFilter().getDescription();
}
}
} catch (UserCancelException ex) {
return;
}
for (int i = 0; i < files.length; i++) {
OpenFile.openFile(files[i], -1);
}
} finally {
running = false;
}
}