Java Code Examples for javax.swing.JFileChooser#setApproveButtonText()

The following examples show how to use javax.swing.JFileChooser#setApproveButtonText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExportTool.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
void createFileChooser() {
  formats = new Hashtable<String, ExportFormat>();
  registerFormat(new ExportGnuplotFormat());
  registerFormat(new ExportXMLFormat());
  // Set the "filesOfTypeLabelText" to "File Format:"
  Object oldFilesOfTypeLabelText = UIManager.put("FileChooser.filesOfTypeLabelText", //$NON-NLS-1$
    ToolsRes.getString("ExportTool.FileChooser.Label.FileFormat"));                  //$NON-NLS-1$
  // Create a new FileChooser
  fc = new JFileChooser(OSPRuntime.chooserDir);
  // Reset the "filesOfTypeLabelText" to previous value
  UIManager.put("FileChooser.filesOfTypeLabelText", oldFilesOfTypeLabelText);          //$NON-NLS-1$
  fc.setDialogType(JFileChooser.SAVE_DIALOG);
  fc.setDialogTitle(ToolsRes.getString("ExportTool.FileChooser.Title"));               //$NON-NLS-1$
  fc.setApproveButtonText(ToolsRes.getString("ExportTool.FileChooser.Button.Export")); // Set export formats //$NON-NLS-1$
  setChooserFormats();
}
 
Example 2
Source File: IdeaUtils.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public static File chooseFile(final Component parent, final boolean filesOnly, final String title, final File selectedFile, final FileFilter filter) {
  final JFileChooser chooser = new JFileChooser(selectedFile);

  chooser.setApproveButtonText("Select");
  if (filter != null) {
    chooser.setFileFilter(filter);
  }

  chooser.setDialogTitle(title);
  chooser.setMultiSelectionEnabled(false);

  if (filesOnly) {
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  } else {
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  }

  if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
    return chooser.getSelectedFile();
  } else {
    return null;
  }
}
 
Example 3
Source File: ScrPrintToPDF.java    From PolyGlot with MIT License 6 votes vote down vote up
private void btnSelectSavePathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectSavePathActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save Language");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf");
    String fileName = core.getCurFileName().replaceAll(".pgd", ".pdf");
    chooser.setFileFilter(filter);
    chooser.setApproveButtonText("Save");
    chooser.setCurrentDirectory(core.getWorkingDirectory());
    chooser.setSelectedFile(new File(fileName));

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        fileName = chooser.getSelectedFile().getAbsolutePath();
        if (!fileName.contains(".pdf")) {
            fileName += ".pdf";
        }            
        txtSavePath.setText(fileName);
    }
}
 
Example 4
Source File: FilePropertyEditor.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
protected void selectFile() {
  ResourceManager rm = ResourceManager.all(FilePropertyEditor.class);

  JFileChooser chooser = UserPreferences.getDefaultFileChooser();
  chooser.setDialogTitle(rm.getString("FilePropertyEditor.dialogTitle"));
  chooser.setApproveButtonText(
    rm.getString("FilePropertyEditor.approveButtonText"));
  chooser.setApproveButtonMnemonic(
    rm.getChar("FilePropertyEditor.approveButtonMnemonic"));

  if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(editor)) {
    File oldFile = (File)getValue();
    File newFile = chooser.getSelectedFile();
    String text = newFile.getAbsolutePath();
    textfield.setText(text);
    firePropertyChange(oldFile, newFile);
  }
}
 
Example 5
Source File: MainFrame.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
private void menuNewProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuNewProjectActionPerformed
  final JFileChooser folderChooser = new JFileChooser();
  folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  folderChooser.setDialogTitle("Create project folder");
  folderChooser.setDialogType(JFileChooser.SAVE_DIALOG);
  folderChooser.setApproveButtonText("Create");
  folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  if (folderChooser.showSaveDialog(Main.getApplicationFrame()) == JFileChooser.APPROVE_OPTION) {
    final File file = folderChooser.getSelectedFile();
    if (file.isDirectory()) {
      if (file.list().length > 0) {
        DialogProviderManager.getInstance().getDialogProvider().msgError(this, "File '" + file.getName() + "' already exists and non-empty!");
      } else {
        prepareAndOpenProjectFolder(file);
      }
    } else if (file.mkdirs()) {
      prepareAndOpenProjectFolder(file);
    } else {
      LOGGER.error("Can't create folder : " + file); //NOI18N
      DialogProviderManager.getInstance().getDialogProvider().msgError(this, "Can't create folder: " + file);
    }
  }
}
 
Example 6
Source File: MainFrame.java    From ios-image-util with MIT License 6 votes vote down vote up
/**
 * Set file path from file chooser dialog.
 *
 * @param textField		TextField to set the file path
 * @param imagePanel	ImagePnel to set the image
 */
private void setFilePathActionPerformed(JTextField textField, ImagePanel imagePanel) {
	JFileChooser chooser = new JFileChooser();
	chooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png"));
	if (!IOSImageUtil.isNullOrWhiteSpace(textField.getText())) {
		File f = new File(textField.getText());
		if (f.getParentFile() != null && f.getParentFile().exists()) {
			chooser.setCurrentDirectory(f.getParentFile());
		}
		if (f.exists()) {
			chooser.setSelectedFile(f);
		}
	} else {
		File dir = getChosenDirectory();
		if (dir != null) chooser.setCurrentDirectory(dir);
	}
	chooser.setApproveButtonText(getResource("button.approve", "Choose"));
	chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
	int returnVal = chooser.showOpenDialog(this);
	if(returnVal == JFileChooser.APPROVE_OPTION) {
		setFilePath(textField, chooser.getSelectedFile(), imagePanel);
    }
}
 
Example 7
Source File: DialogProviderManager.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public File msgOpenFileDialog(@Nullable final Component parentComponent, @Nonnull String id, @Nonnull String title, @Nullable File defaultFolder, boolean filesOnly, @Nonnull @MustNotContainNull FileFilter[] fileFilters, @Nonnull String approveButtonText) {
  final File folderToUse;
  if (defaultFolder == null) {
    folderToUse = cacheOpenFileThroughDialog.find(null, id);
  } else {
    folderToUse = defaultFolder;
  }

  final JFileChooser fileChooser = new JFileChooser(folderToUse);
  fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
  fileChooser.setDialogTitle(title);
  fileChooser.setApproveButtonText(approveButtonText);
  for (final FileFilter f : fileFilters) {
    fileChooser.addChoosableFileFilter(f);
  }
  if (fileFilters.length != 0) {
    fileChooser.setFileFilter(fileFilters[0]);
  }
  fileChooser.setAcceptAllFileFilterUsed(true);
  fileChooser.setMultiSelectionEnabled(false);

  File result = null;
  if (fileChooser.showDialog(GetUtils.ensureNonNull(
      parentComponent == null ? null : SwingUtilities.windowForComponent(parentComponent),
      Main.getApplicationFrame()),
      approveButtonText) == JFileChooser.APPROVE_OPTION) {
    result = cacheOpenFileThroughDialog.put(id, fileChooser.getSelectedFile());
  }

  return result;
}
 
Example 8
Source File: UtilFunctions.java    From yeti with MIT License 5 votes vote down vote up
public static String openFile(String fileExtension) {
    JFileChooser dlgFile = new JFileChooser();
    dlgFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    dlgFile.setApproveButtonText("Open");

    int returnVal = dlgFile.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = dlgFile.getSelectedFile();
        return file.getAbsolutePath();
    }
    return "";
}
 
Example 9
Source File: FileChooserBuilder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void prepareFileChooser(JFileChooser chooser) {
    chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY
            : filesOnly ? JFileChooser.FILES_ONLY :
            JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setFileHidingEnabled(fileHiding);
    chooser.setControlButtonsAreShown(controlButtonsShown);
    chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter);
    if (title != null) {
        chooser.setDialogTitle(title);
    }
    if (approveText != null) {
        chooser.setApproveButtonText(approveText);
    }
    if (badger != null) {
        chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger),
                chooser.getFileSystemView()));
    }
    if (PREVENT_SYMLINK_TRAVERSAL) {
        FileUtil.preventFileChooserSymlinkTraversal(chooser,
                chooser.getCurrentDirectory());
    }
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    if (aDescription != null) {
        chooser.getAccessibleContext().setAccessibleDescription(aDescription);
    }
    if (!filters.isEmpty()) {
        for (FileFilter f : filters) {
            chooser.addChoosableFileFilter(f);
        }
    }
}
 
Example 10
Source File: ServerFileUtils.java    From chipster with MIT License 5 votes vote down vote up
public static void hideApproveButton(JFileChooser fileChooser) {
	// this will initialize the button and its parent component
	fileChooser.setApproveButtonText("approveButton");
	JButton button = lookupButton(fileChooser, "approveButton");
	// reset approve button text
	fileChooser.setApproveButtonText(null);
	// hide it
	button.setVisible(false);
}
 
Example 11
Source File: DialogProviderManager.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public File msgSaveFileDialog(@Nullable final Component parentComponent, @Nonnull final String id, @Nonnull final String title, @Nullable final File defaultFolder, final boolean filesOnly, @Nonnull @MustNotContainNull final FileFilter[] fileFilters, @Nonnull final String approveButtonText) {
  final File folderToUse;
  if (defaultFolder == null) {
    folderToUse = cacheSaveFileThroughDialog.find(null, id);
  } else {
    folderToUse = defaultFolder;
  }

  final JFileChooser fileChooser = new JFileChooser(folderToUse);
  fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
  fileChooser.setDialogTitle(title);
  fileChooser.setApproveButtonText(approveButtonText);
  fileChooser.setAcceptAllFileFilterUsed(true);
  for (final FileFilter f : fileFilters) {
    fileChooser.addChoosableFileFilter(f);
  }
  if (fileFilters.length != 0) {
    fileChooser.setFileFilter(fileFilters[0]);
  }
  fileChooser.setMultiSelectionEnabled(false);

  File result = null;
  if (fileChooser.showDialog(GetUtils.ensureNonNull(
      parentComponent == null ? null : SwingUtilities.windowForComponent(parentComponent),
      Main.getApplicationFrame()),
      approveButtonText) == JFileChooser.APPROVE_OPTION
  ) {
    result = cacheSaveFileThroughDialog.put(id, fileChooser.getSelectedFile());
  }

  return result;
}
 
Example 12
Source File: LoadDialog.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a dialog to choose a file to load.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param frame The owner frame.
 * @param directory The directory to display when choosing the file.
 * @param fileFilters The available file filters in the dialog.
 */
public LoadDialog(FreeColClient freeColClient, JFrame frame,
        File directory, FileFilter[] fileFilters) {
    super(freeColClient, frame);

    final JFileChooser fileChooser = new JFileChooser(directory);
    if (fileFilters.length > 0) {
        for (FileFilter fileFilter : fileFilters) {
            fileChooser.addChoosableFileFilter(fileFilter);
        }
        fileChooser.setFileFilter(fileFilters[0]);
        fileChooser.setAcceptAllFileFilterUsed(false);
    }
    fileChooser.setControlButtonsAreShown(true);
    fileChooser.setApproveButtonText(Messages.message("ok"));
    //fileChooser.setCancelButtonText(Messages.message("cancel"));
    fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setFileHidingEnabled(false);
    fileChooser.addActionListener((ActionEvent ae) -> {
            final String cmd = ae.getActionCommand();
            File value = (JFileChooser.APPROVE_SELECTION.equals(cmd))
                ? ((JFileChooser)ae.getSource()).getSelectedFile()
                : cancelFile;
            setValue(value);
        });

    List<ChoiceItem<File>> c = choices();
    initializeDialog(frame, DialogType.QUESTION, true, fileChooser, null, c);
}
 
Example 13
Source File: ResultsManager.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
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);
}
 
Example 14
Source File: ResultsManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void exportSnapshots(final FileObject[] selectedSnapshots) {
    assert (selectedSnapshots != null);
    assert (selectedSnapshots.length > 0);

    final String[] fileName = new String[1], fileExt = new String[1];
    final FileObject[] dir = new FileObject[1];
    if (selectedSnapshots.length == 1) {
        SelectedFile sf = selectSnapshotTargetFile(selectedSnapshots[0].getName(),
                            selectedSnapshots[0].getExt().equals(HEAPDUMP_EXTENSION));

        if ((sf != null) && checkFileExists(sf)) {
            fileName[0] = sf.fileName;
            fileExt[0] = sf.fileExt;
            dir[0] = sf.folder;
        } else { // dialog cancelled by the user
            return;
        }
    } else {
        JFileChooser chooser = new JFileChooser();

        if (exportDir != null) {
            chooser.setCurrentDirectory(exportDir);
        }

        chooser.setDialogTitle(Bundle.ResultsManager_SelectDirDialogCaption());
        chooser.setApproveButtonText(Bundle.ResultsManager_SaveButtonName());
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);

        if (chooser.showSaveDialog(WindowManager.getDefault().getMainWindow()) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();

            if (!file.exists()) {
                if (!ProfilerDialogs.displayConfirmation(
                        Bundle.ResultsManager_DirectoryDoesntExistMsg(), 
                        Bundle.ResultsManager_DirectoryDoesntExistCaption())) {
                    return; // cancelled by the user
                }

                file.mkdir();
            }

            exportDir = file;

            dir[0] = FileUtil.toFileObject(FileUtil.normalizeFile(file));
        } else { // dialog cancelled
            return;
        }
    }
    final ProgressHandle ph = ProgressHandle.createHandle(Bundle.MSG_SavingSnapshots());
    ph.setInitialDelay(500);
    ph.start();
    ProfilerUtils.runInProfilerRequestProcessor(new Runnable() {
        @Override
        public void run() {
            try {
                for (int i = 0; i < selectedSnapshots.length; i++) {
                    exportSnapshot(selectedSnapshots[i], dir[0], fileName[0] != null ? fileName[0] : selectedSnapshots[i].getName(), fileExt[0] != null ? fileExt[0] : selectedSnapshots[i].getExt());
                }
            } finally {
                ph.finish();
            }
        }
    });
}
 
Example 15
Source File: J2SEPlatformCustomizer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean select(
    final PathModel model,
    final File[] currentDir,
    final Component parentComponent) {
    final JFileChooser chooser = new JFileChooser ();
    chooser.setMultiSelectionEnabled (true);
    String title = null;
    String message = null;
    String approveButtonName = null;
    String approveButtonNameMne = null;
    if (model.type == SOURCES) {
        title = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_OpenSources");
        message = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_Sources");
        approveButtonName = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_OpenSources");
        approveButtonNameMne = NbBundle.getMessage (J2SEPlatformCustomizer.class,"MNE_OpenSources");
    } else if (model.type == JAVADOC) {
        title = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_OpenJavadoc");
        message = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_Javadoc");
        approveButtonName = NbBundle.getMessage (J2SEPlatformCustomizer.class,"TXT_OpenJavadoc");
        approveButtonNameMne = NbBundle.getMessage (J2SEPlatformCustomizer.class,"MNE_OpenJavadoc");
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText(approveButtonName);
    chooser.setApproveButtonMnemonic (approveButtonNameMne.charAt(0));
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if (Utilities.isMac()) {
        //New JDKs and JREs are bundled into package, allow JFileChooser to navigate in
        chooser.putClientProperty("JFileChooser.packageIsTraversable", "always");   //NOI18N
    }
    //#61789 on old macosx (jdk 1.4.1) these two method need to be called in this order.
    chooser.setAcceptAllFileFilterUsed( false );
    chooser.setFileFilter (new ArchiveFileFilter(message,new String[] {"ZIP","JAR"}));   //NOI18N
    if (currentDir[0] != null) {
        chooser.setCurrentDirectory(currentDir[0]);
    }
    if (chooser.showOpenDialog(parentComponent) == JFileChooser.APPROVE_OPTION) {
        File[] fs = chooser.getSelectedFiles();
        boolean addingFailed = false;
        for (File f : fs) {
            //XXX: JFileChooser workaround (JDK bug #5075580), double click on folder returns wrong file
            // E.g. for /foo/src it returns /foo/src/src
            // Try to convert it back by removing last invalid name component
            if (!f.exists()) {
                File parent = f.getParentFile();
                if (parent != null && f.getName().equals(parent.getName()) && parent.exists()) {
                    f = parent;
                }
            }
            if (f.exists()) {
                addingFailed|=!model.addPath (f);
            }
        }
        if (addingFailed) {
            new NotifyDescriptor.Message (NbBundle.getMessage(J2SEPlatformCustomizer.class,"TXT_CanNotAddResolve"),
                    NotifyDescriptor.ERROR_MESSAGE);
        }
        currentDir[0] = FileUtil.normalizeFile(chooser.getCurrentDirectory());
        return true;
    }
    return false;
}
 
Example 16
Source File: CustomizerSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addPathElement () {
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setMultiSelectionEnabled (true);
    String title = null;
    String message = null;
    String approveButtonName = null;
    String approveButtonNameMne = null;
    if (SOURCES.equals(this.type)) {
        title = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenSources");
        message = NbBundle.getMessage (CustomizerSupport.class,"TXT_Sources");
        approveButtonName = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenSources");
        approveButtonNameMne = NbBundle.getMessage (CustomizerSupport.class,"MNE_OpenSources");
    } else if (JAVADOC.equals(this.type)) {
        title = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenJavadoc");
        message = NbBundle.getMessage (CustomizerSupport.class,"TXT_Javadoc");
        approveButtonName = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenJavadoc");
        approveButtonNameMne = NbBundle.getMessage (CustomizerSupport.class,"MNE_OpenJavadoc");
    } else {
        throw new IllegalStateException("Can't add element for classpath"); // NOI18N
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText(approveButtonName);
    chooser.setApproveButtonMnemonic (approveButtonNameMne.charAt(0));
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    //#61789 on old macosx (jdk 1.4.1) these two method need to be called in this order.
    chooser.setAcceptAllFileFilterUsed( false );
    chooser.setFileFilter (new SimpleFileFilter(message,new String[] {"ZIP","JAR"}));   //NOI18N
    if (this.currentDir != null && currentDir.exists()) {
        chooser.setCurrentDirectory(this.currentDir);
    }
    if (chooser.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
        File[] fs = chooser.getSelectedFiles();
        PathModel model = (PathModel) this.resources.getModel();
        boolean addingFailed = false;
        int firstIndex = this.resources.getModel().getSize();
        for (int i = 0; i < fs.length; i++) {
            File f = fs[i];
            //XXX: JFileChooser workaround (JDK bug #5075580), double click on folder returns wrong file
            // E.g. for /foo/src it returns /foo/src/src
            // Try to convert it back by removing last invalid name component
            if (!f.exists()) {
                File parent = f.getParentFile();
                if (parent != null && f.getName().equals(parent.getName()) && parent.exists()) {
                    f = parent;
                }
            }
            addingFailed|=!model.addPath (f);
        }
        if (addingFailed) {
            new NotifyDescriptor.Message (NbBundle.getMessage(CustomizerSupport.class,"TXT_CanNotAddResolve"),
                    NotifyDescriptor.ERROR_MESSAGE);
        }
        int lastIndex = this.resources.getModel().getSize()-1;
        if (firstIndex<=lastIndex) {
            int[] toSelect = new int[lastIndex-firstIndex+1];
            for (int i = 0; i < toSelect.length; i++) {
                toSelect[i] = firstIndex+i;
            }
            this.resources.setSelectedIndices(toSelect);
        }
        this.currentDir = FileUtil.normalizeFile(chooser.getCurrentDirectory());
    }
}
 
Example 17
Source File: ScrMainMenu.java    From PolyGlot with MIT License 4 votes vote down vote up
/**
 * Export dictionary to excel file
 */
private void exportToExcel() {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Export Language to Excel");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
    chooser.setFileFilter(filter);
    chooser.setApproveButtonText("Save");
    chooser.setCurrentDirectory(core.getWorkingDirectory());

    String fileName = core.getCurFileName().replaceAll(".pgd", ".xls");
    chooser.setSelectedFile(new File(fileName));

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        fileName = chooser.getSelectedFile().getAbsolutePath();
    } else {
        return;
    }

    if (!fileName.contains(".xls")) {
        fileName += ".xls";
    }

    if (!new File(fileName).exists()
            || InfoBox.actionConfirmation("Overwrite File?", "File with this name and location already exists. Continue/Overwrite?", this)) {
        try {
            Java8Bridge.exportExcelDict(fileName, core,
                    InfoBox.actionConfirmation("Excel Export",
                            "Export all declensions? (Separates parts of speech into individual tabs)",
                            core.getRootWindow()));

            // only prompt user to open if Desktop supported
            if (Desktop.isDesktopSupported()) {
                if (InfoBox.actionConfirmation("Export Sucess", "Language exported to " + fileName + ".\nOpen now?", this)) {
                    Desktop.getDesktop().open(new File(fileName));
                }
            } else {
                InfoBox.info("Export Status", "Language exported to " + fileName + ".", core.getRootWindow());
            }
        } catch (IOException e) {
            IOHandler.writeErrorLog(e);
            InfoBox.info("Export Problem", e.getLocalizedMessage(), core.getRootWindow());
        }
    }
}
 
Example 18
Source File: SvnProperties.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void loadFromFile() {
    final JFileChooser chooser = new AccessibleJFileChooser(NbBundle.getMessage(SvnProperties.class, "ACSD_Properties"));
    chooser.setDialogTitle(NbBundle.getMessage(SvnProperties.class, "CTL_Load_Value_Title"));
    chooser.setMultiSelectionEnabled(false);
    javax.swing.filechooser.FileFilter[] fileFilters = chooser.getChoosableFileFilters();
    for (int i = 0; i < fileFilters.length; i++) {
        javax.swing.filechooser.FileFilter fileFilter = fileFilters[i];
        chooser.removeChoosableFileFilter(fileFilter);
    }

    chooser.setCurrentDirectory(roots[0].getParentFile()); // NOI18N
    chooser.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
        @Override
        public boolean accept(File f) {
            return f.exists();
        }
        @Override
        public String getDescription() {
            return "";
        }
    });

    chooser.setDialogType(JFileChooser.OPEN_DIALOG);
    chooser.setApproveButtonMnemonic(NbBundle.getMessage(SvnProperties.class, "MNE_LoadValue").charAt(0));
    chooser.setApproveButtonText(NbBundle.getMessage(SvnProperties.class, "CTL_LoadValue"));
    DialogDescriptor dd = new DialogDescriptor(chooser, NbBundle.getMessage(SvnProperties.class, "CTL_Load_Value_Title"));
    dd.setOptions(new Object[0]);
    final Dialog dialog = DialogDisplayer.getDefault().createDialog(dd);

    chooser.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String state = e.getActionCommand();
            if (state.equals(JFileChooser.APPROVE_SELECTION)) {
                File source = chooser.getSelectedFile();

                if (Utils.isFileContentText(source)) {
                    if (source.canRead()) {
                        StringWriter sw = new StringWriter();
                        try {
                            Utils.copyStreamsCloseAll(sw, new FileReader(source));
                            panel.txtAreaValue.setText(sw.toString());
                        } catch (IOException ex) {
                            Subversion.LOG.log(Level.SEVERE, null, ex);
                        }
                    }
                } else {
                    handleBinaryFile(source);
                }
            }
            dialog.dispose();
        }
    });
    dialog.setVisible(true);

}
 
Example 19
Source File: PatchAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private File getPatchFor(FileObject fo) {
       JFileChooser chooser = new JFileChooser();
       String patchDirPath = DiffModuleConfig.getDefault().getPreferences().get(PREF_RECENT_PATCH_PATH, System.getProperty("user.home"));
       File patchDir = new File(patchDirPath);
       while (!patchDir.isDirectory()) {
           patchDir = patchDir.getParentFile();
           if (patchDir == null) {
               patchDir = new File(System.getProperty("user.home"));
               break;
           }
       }
       FileUtil.preventFileChooserSymlinkTraversal(chooser, patchDir);
       chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
       String title = NbBundle.getMessage(PatchAction.class,
           (fo.isData()) ? "TITLE_SelectPatchForFile"
                         : "TITLE_SelectPatchForFolder", fo.getNameExt());
       chooser.setDialogTitle(title);

       // setup filters, default one filters patch files
       FileFilter patchFilter = new javax.swing.filechooser.FileFilter() {
           @Override
           public boolean accept(File f) {
               return f.getName().endsWith("diff") || f.getName().endsWith("patch") || f.isDirectory();  // NOI18N
           }
           @Override
           public String getDescription() {
               return NbBundle.getMessage(PatchAction.class, "CTL_PatchDialog_FileFilter");
           }
       };
       chooser.addChoosableFileFilter(patchFilter);
       chooser.setFileFilter(patchFilter);

       chooser.setApproveButtonText(NbBundle.getMessage(PatchAction.class, "BTN_Patch"));
       chooser.setApproveButtonMnemonic(NbBundle.getMessage(PatchAction.class, "BTN_Patch_mnc").charAt(0));
       chooser.setApproveButtonToolTipText(NbBundle.getMessage(PatchAction.class, "BTN_Patch_tooltip"));
       HelpCtx ctx = new HelpCtx(PatchAction.class.getName());
       DialogDescriptor descriptor = new DialogDescriptor( chooser, title, true, new Object[0], null, 0, ctx, null );
       final Dialog dialog = DialogDisplayer.getDefault().createDialog( descriptor );
       dialog.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(PatchAction.class, "ACSD_PatchDialog"));

       ChooserListener listener = new PatchAction.ChooserListener(dialog,chooser);
chooser.addActionListener(listener);
       dialog.setVisible(true);

       File selectedFile = listener.getFile();
       if (selectedFile != null) {
           DiffModuleConfig.getDefault().getPreferences().put(PREF_RECENT_PATCH_PATH, selectedFile.getParentFile().getAbsolutePath());
       }
       return selectedFile;
   }
 
Example 20
Source File: ScrMainMenu.java    From PolyGlot with MIT License 4 votes vote down vote up
/**
 * Provides dialog for Save As, and returns boolean to determine whether
 * file save should take place. DOES NOT SAVE.
 *
 * @return true if file saved, false otherwise
 */
private boolean saveFileAsDialog() {
    boolean ret = false;
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PolyGlot Dictionaries", "pgd");
    String curFileName = core.getCurFileName();

    chooser.setDialogTitle("Save Language");
    chooser.setFileFilter(filter);
    chooser.setApproveButtonText("Save");
    if (curFileName.isEmpty()) {
        chooser.setCurrentDirectory(core.getWorkingDirectory());
    } else {
        chooser.setCurrentDirectory(IOHandler.getDirectoryFromPath(curFileName));
        chooser.setSelectedFile(IOHandler.getFileFromPath(curFileName));
    }

    String fileName;

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        fileName = chooser.getSelectedFile().getAbsolutePath();
        // if user has not provided an extension, add one
        if (!fileName.contains(".pgd")) {
            fileName += ".pgd";
        }

        if (IOHandler.fileExists(fileName)) {
            int overWrite = InfoBox.yesNoCancel("Overwrite Dialog",
                    "Overwrite existing file? " + fileName, core.getRootWindow());

            if (overWrite == JOptionPane.NO_OPTION) {
                ret = saveFileAsDialog();
            } else if (overWrite == JOptionPane.YES_OPTION) {
                core.setCurFileName(fileName);
                ret = true;
            }
        } else {
            core.setCurFileName(fileName);
            ret = true;
        }
    }

    return ret;
}