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

The following examples show how to use javax.swing.JFileChooser#getSelectedFile() . 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: VideoPlayer.java    From open-ig with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Export the selected videos as PNG images. */
void doExport() {
	JFileChooser jfc = new JFileChooser(lastDir != null ? lastDir : new File("."));
	jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
		lastDir = jfc.getSelectedFile();
		int[] sels = videoTable.getSelectedRows();
		final List<AVExport> exportList = new ArrayList<>();
           for (int sel : sels) {
               VideoEntry ve = videoModel.rows.get(videoTable.convertRowIndexToModel(sel));

               AVExport ave = new AVExport();
               ave.video = rl.get(ve.path + "/" + ve.name, ResourceType.VIDEO);
               if (ve.audio != null && !ve.audio.isEmpty()) {
                   ave.audio = rl.getExactly(ve.audio, ve.path + "/" + ve.name, ResourceType.AUDIO);
               }
               ave.naming = lastDir.getAbsolutePath() + "/" + ve.name + "_%05d.png";
               exportList.add(ave);
           }
		doExportGUI(exportList);
	}
}
 
Example 2
Source File: TypesConfigFrame.java    From ontopia with Apache License 2.0 6 votes vote down vote up
protected String promptForFile() {
  JFileChooser dialog = new JFileChooser(lastIconPath);

  dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
  dialog.setAcceptAllFileFilterUsed(false);
  dialog.setDialogTitle(Messages.getString("Viz.SelectIcon"));
  dialog.setSelectedFile(new File(filenameField.getText()));

  SimpleFileFilter filter = new SimpleFileFilter(Messages
      .getString("Viz.ImageFiles"));
  filter.addExtension("JPG");
  filter.addExtension("JPEG");
  filter.addExtension("GIF");
  filter.addExtension("PNG");

  dialog.setFileFilter(filter);

  dialog.showOpenDialog(this);
  File file = dialog.getSelectedFile();
  if (file == null) return null;

  lastIconPath = file.getPath();
  return file.getAbsolutePath();
}
 
Example 3
Source File: AddWebServiceDlg.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void jBtnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnBrowseActionPerformed

    jRbnFilesystem.setSelected(false);
    jRbnFilesystem.setSelected(true);
    enableControls();

    JFileChooser chooser = new JFileChooser(previousDirectory);
    chooser.setMultiSelectionEnabled(false);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.addChoosableFileFilter(WSDL_FILE_FILTER);
    chooser.setFileFilter(WSDL_FILE_FILTER);

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        File wsdlFile = chooser.getSelectedFile();
        jTxtLocalFilename.setText(wsdlFile.getAbsolutePath());
        previousDirectory = wsdlFile.getPath();
    }
}
 
Example 4
Source File: AnalyseTokensDialog.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void saveAnalysis() {
    JFileChooser chooser =
            new WritableFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory());
    File file = null;
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }

            try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) {
                out.write(getErrorsArea().getText());
                out.write(getDetailsArea().getText());
            }

        } catch (Exception e) {
            View.getSingleton()
                    .showWarningDialog(messages.getString("tokengen.analyse.save.error"));
            log.error(e.getMessage(), e);
        }
    }
}
 
Example 5
Source File: PanelProjectLocationVisual.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void browseLocationAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseLocationAction
    String command = evt.getActionCommand();        
    if ( "BROWSE".equals( command ) ) { // NOI18N                
        JFileChooser chooser = new JFileChooser ();
        FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
        chooser.setDialogTitle(NbBundle.getMessage(PanelProjectLocationVisual.class,"LBL_NWP1_SelectProjectLocation"));
        chooser.setFileSelectionMode (JFileChooser.DIRECTORIES_ONLY);
        String path = this.projectLocationTextField.getText();
        if (path.length() > 0) {
            File f = new File (path);
            if (f.exists ()) {
                chooser.setSelectedFile(f);
            }
        }
        if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) { //NOI18N
            File projectDir = chooser.getSelectedFile();
            projectLocationTextField.setText( FileUtil.normalizeFile(projectDir).getAbsolutePath() );
        }            
        panel.fireChangeEvent();
    }
}
 
Example 6
Source File: TokenPanel.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void saveTokens() {
    JFileChooser chooser =
            new WritableFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory());
    File file = null;
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }

            CharacterFrequencyMap cfm = new CharacterFrequencyMap();

            for (int i = 0; i < this.resultsModel.getRowCount(); i++) {
                MessageSummary msg = this.resultsModel.getMessage(i);
                if (msg.getToken() != null) {
                    cfm.addToken(msg.getToken());
                }
            }

            cfm.save(file);

        } catch (Exception e) {
            View.getSingleton()
                    .showWarningDialog(
                            extension.getMessages().getString("tokengen.generate.save.error"));
            log.error(e.getMessage(), e);
        }
    }
}
 
Example 7
Source File: FrmGifAnimator.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void jButton_CreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CreateActionPerformed
    // TODO add your handling code here:
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    
    String path = System.getProperty("user.dir");
    File pathDir = new File(path);
    JFileChooser saveDlg = new JFileChooser();
    saveDlg.setAcceptAllFileFilterUsed(false);
    saveDlg.setCurrentDirectory(pathDir);
    String[] fileExts = new String[]{"gif"};
    GenericFileFilter gifFileFilter = new GenericFileFilter(fileExts, "Gif File (*.gif)");
    saveDlg.setFileFilter(gifFileFilter);
    if (JFileChooser.APPROVE_OPTION == saveDlg.showSaveDialog(this)) {
        File outfile = saveDlg.getSelectedFile();
        String extent = ((GenericFileFilter) saveDlg.getFileFilter()).getFileExtent();
        String fileName = outfile.getAbsolutePath();
        if (!fileName.substring(fileName.length() - extent.length()).equals(extent)) {
            fileName = fileName + "." + extent;
        }            

        DefaultListModel listModel = (DefaultListModel) this.jList_ImageFiles.getModel();
        List<String> fns = new ArrayList<String>();
        for (int i = 0; i < listModel.getSize(); i++) {
            fns.add(listModel.get(i).toString());
        }
        int delay = Integer.parseInt(this.jTextField_Delay.getText());
        int repeat = Integer.parseInt(this.jTextField_Repeat.getText());
        ImageUtil.createGifAnimator(fns, fileName, delay, repeat);
        JOptionPane.showMessageDialog(null, "Gif animator file is created!");
    }
    
    this.setCursor(Cursor.getDefaultCursor());
}
 
Example 8
Source File: AResizerFrame.java    From AndroidResizer with MIT License 5 votes vote down vote up
private void BrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BrowseButtonActionPerformed
    //    new FolderChooser().setVisible(true);

    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.showOpenDialog(null);
    //chooser.
    originalDirectory = chooser.getSelectedFile();
    String directoryName = originalDirectory.getAbsolutePath();

    FileField.setText(directoryName);
    // TODO add your handling code here:
}
 
Example 9
Source File: FileUtils.java    From PyramidShader with GNU General Public License v3.0 5 votes vote down vote up
public static String askDirectory(java.awt.Frame frame,
        String message,
        boolean load,
        String defaultDirectory) throws IOException {

    if (FileUtils.IS_MAC_OSX) {
        try {
            System.setProperty("apple.awt.fileDialogForDirectories", "true");
            FileDialog fd = new FileDialog(frame, message, load ? FileDialog.LOAD : FileDialog.SAVE);
            fd.setFile(defaultDirectory);
            fd.setVisible(true);
            String fileName = fd.getFile();
            String directory = fd.getDirectory();
            return (fileName == null || directory == null) ? null : directory + fileName;
        } finally {
            System.setProperty("apple.awt.fileDialogForDirectories", "false");
        }
    } else {
        JFileChooser fc = new JFileChooser(defaultDirectory);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setDialogTitle(message);
        fc.showOpenDialog(null);

        File selFile = fc.getSelectedFile();
        return selFile.getCanonicalPath();
    }
}
 
Example 10
Source File: Utils.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public static File openDialog(String desc, String... fileFormat) {
    JFileChooser fileChooser = createFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    if (fileFormat != null && fileFormat.length > 0) {
        fileChooser.setFileFilter(new FileNameExtensionFilter(desc, fileFormat));
    }
    int option = fileChooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFile();
    }
    return null;
}
 
Example 11
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 12
Source File: GrammarVizController.java    From grammarviz2_src with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements a listener for the "Browse" button at GUI; opens FileChooser and so on.
 * 
 * @return the action listener.
 */
public ActionListener getBrowseFilesListener() {

  ActionListener selectDataActionListener = new ActionListener() {

    public void actionPerformed(ActionEvent e) {

      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setDialogTitle("Select Data File");

      String filename = model.getDataFileName();
      if (!((null == filename) || filename.isEmpty())) {
        fileChooser.setSelectedFile(new File(filename));
      }

      if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();

        // here it calls to model -informing about the selected file.
        //
        model.setDataSource(file.getAbsolutePath());
      }
    }

  };
  return selectDataActionListener;
}
 
Example 13
Source File: CEOCSTN2Shop2.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public void print(final CEOCSTNPlanningProblem problem, final String packageName) throws IOException {
	this.packageName = packageName;
	JFileChooser chooser = new JFileChooser();
	chooser.setDialogTitle("Domain-File");
	chooser.showOpenDialog(null);
	File domainFile = chooser.getSelectedFile();

	this.printDomain(domainFile);

	chooser.setDialogTitle("Problem-File");
	chooser.showOpenDialog(null);
	File problemFile = chooser.getSelectedFile();
	this.printProblem(problem, problemFile);
}
 
Example 14
Source File: ScatterPlotter.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void save() {
	JFileChooser chooser = SwingTools.createFileChooser("file_chooser.save", null, false, new FileFilter[0]);
	if (chooser.showSaveDialog(ScatterPlotter.this) == JFileChooser.APPROVE_OPTION) {
		File file = chooser.getSelectedFile();
		try (FileWriter fw = new FileWriter(file); PrintWriter out = new PrintWriter(fw)) {
			dataTable.write(out);
		} catch (Exception ex) {
			SwingTools.showSimpleErrorMessage("cannot_write_to_file_0", ex, file);
		}
	}
}
 
Example 15
Source File: AboutDialogControls.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private void saveFileAs(final File file) {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle(NbBundle.getMessage(AboutDialogControls.class, "CAPTION_Save_logfile")); // NOI18N
        chooser.setSelectedFile(new File(lastLogfileSave));
        if (chooser.showSaveDialog(WindowManager.getDefault().getMainWindow()) == JFileChooser.APPROVE_OPTION) {
            final File copy = chooser.getSelectedFile();
//            if (copy.isFile()) // TODO: show a confirmation dialog for already existing file
            lastLogfileSave = copy.getAbsolutePath();
            VisualVM.getInstance().runTask(new Runnable() {
                public void run() {
                    ProgressHandle pHandle = null;
                    try {
                        pHandle = ProgressHandleFactory.createHandle(
                                NbBundle.getMessage(AboutDialogControls.class,
                                "MSG_Saving_logfile", file.getName()));  // NOI18N
                        pHandle.setInitialDelay(0);
                        pHandle.start();
                        if (!Utils.copyFile(file, copy)) JOptionPane.showMessageDialog(AboutDialog.getInstance().getDialog(), 
                            NbBundle.getMessage(AboutDialogControls.class, "MSG_Save_logfile_failed"),   // NOI18N
                            NbBundle.getMessage(AboutDialogControls.class, "CAPTION_Save_logfile_failed"),    // NOI18N
                            JOptionPane.ERROR_MESSAGE);
                    } finally {
                        final ProgressHandle pHandleF = pHandle;
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() { if (pHandleF != null) pHandleF.finish(); }
                        });
                    }
                }
            });
        }
    }
 
Example 16
Source File: ControlUtils.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Loads control parameters from a text file using a dialog box.
 */
public static void loadParameters(Control control, Component parent) {
  JFileChooser chooser = new JFileChooser(new File(OSPRuntime.chooserDir));
	FontSizer.setFonts(chooser, FontSizer.getLevel());
  int result = chooser.showOpenDialog(parent);
  if(result==JFileChooser.APPROVE_OPTION) {
    try {
      BufferedReader inFile = new BufferedReader(new FileReader(chooser.getSelectedFile()));
      readFile(control, inFile);
      inFile.close();
    } catch(Exception ex) {
      System.err.println(ex.getMessage());
    }
  }
}
 
Example 17
Source File: SupportPackageAction.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Show file "Save As" dialog
 *
 * @return File selected by the user or null if no file was selected.
 */
private File getSaveAsDirectory() {

    final JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setDialogTitle(Bundle.MSG_SaveAsTitle());
    chooser.setMultiSelectionEnabled(false);
    chooser.setCurrentDirectory(new File(System.getProperty("user.home")));

    if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(WindowManager.getDefault().getMainWindow())) {
        return chooser.getSelectedFile();
    } else {
        return null;
    }
}
 
Example 18
Source File: BrowserMDIFrame.java    From ApkToolPlus with Apache License 2.0 5 votes vote down vote up
private void doOpenClassFile() {

		JFileChooser fileChooser = getClassesFileChooser();
		int result = fileChooser.showOpenDialog(this);
		if (result == JFileChooser.APPROVE_OPTION) {
			repaintNow();
			setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			File file = fileChooser.getSelectedFile();
			classesChooserPath = fileChooser.getCurrentDirectory()
					.getAbsolutePath();

			BrowserInternalFrame frame;
			if (file.getPath().toLowerCase().endsWith(".class")) {
				frame = openClassFromFile(file);
			} else {
				frame = openClassFromJar(file);
			}

			if (frame != null) {
				try {
					frame.setMaximum(true);
				} catch (PropertyVetoException ex) {
				}
			}
			setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		}
	}
 
Example 19
Source File: ExportImage.java    From Logisim with GNU General Public License v3.0 4 votes vote down vote up
static void doExport(Project proj) {
	// First display circuit/parameter selection dialog
	Frame frame = proj.getFrame();
	CircuitJList list = new CircuitJList(proj, true);
	if (list.getModel().getSize() == 0) {
		JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("exportEmptyCircuitsMessage"),
				Strings.get("exportEmptyCircuitsTitle"), JOptionPane.YES_NO_OPTION);
		return;
	}
	OptionsPanel options = new OptionsPanel(list);
	int action = JOptionPane.showConfirmDialog(frame, options, Strings.get("exportImageSelect"),
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
	if (action != JOptionPane.OK_OPTION)
		return;
	List<Circuit> circuits = list.getSelectedCircuits();
	double scale = options.getScale();
	boolean printerView = options.getPrinterView();
	if (circuits.isEmpty())
		return;

	ImageFileFilter filter;
	int fmt = options.getImageFormat();
	switch (options.getImageFormat()) {
	case FORMAT_GIF:
		filter = new ImageFileFilter(fmt, Strings.getter("exportGifFilter"), new String[] { "gif" });
		break;
	case FORMAT_PNG:
		filter = new ImageFileFilter(fmt, Strings.getter("exportPngFilter"), new String[] { "png" });
		break;
	case FORMAT_JPG:
		filter = new ImageFileFilter(fmt, Strings.getter("exportJpgFilter"),
				new String[] { "jpg", "jpeg", "jpe", "jfi", "jfif", "jfi" });
		break;
	default:
		System.err.println("unexpected format; aborted"); // OK
		return;
	}

	// Then display file chooser
	Loader loader = proj.getLogisimFile().getLoader();
	JFileChooser chooser = loader.createChooser();
	if (circuits.size() > 1) {
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		chooser.setDialogTitle(Strings.get("exportImageDirectorySelect"));
	} else {
		chooser.setFileFilter(filter);
		chooser.setDialogTitle(Strings.get("exportImageFileSelect"));
	}
	int returnVal = chooser.showDialog(frame, Strings.get("exportImageButton"));
	if (returnVal != JFileChooser.APPROVE_OPTION)
		return;

	// Determine whether destination is valid
	File dest = chooser.getSelectedFile();
	chooser.setCurrentDirectory(dest.isDirectory() ? dest : dest.getParentFile());
	if (dest.exists()) {
		if (!dest.isDirectory()) {
			int confirm = JOptionPane.showConfirmDialog(proj.getFrame(), Strings.get("confirmOverwriteMessage"),
					Strings.get("confirmOverwriteTitle"), JOptionPane.YES_NO_OPTION);
			if (confirm != JOptionPane.YES_OPTION)
				return;
		}
	} else {
		if (circuits.size() > 1) {
			boolean created = dest.mkdir();
			if (!created) {
				JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("exportNewDirectoryErrorMessage"),
						Strings.get("exportNewDirectoryErrorTitle"), JOptionPane.YES_NO_OPTION);
				return;
			}
		}
	}

	// Create the progress monitor
	ProgressMonitor monitor = new ProgressMonitor(frame, Strings.get("exportImageProgress"), null, 0, 10000);
	monitor.setMillisToDecideToPopup(100);
	monitor.setMillisToPopup(200);
	monitor.setProgress(0);

	// And start a thread to actually perform the operation
	// (This is run in a thread so that Swing will update the
	// monitor.)
	new ExportThread(frame, frame.getCanvas(), dest, filter, circuits, scale, printerView, monitor).start();

}
 
Example 20
Source File: ExportAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private SelectedFile selectExportTargetFile(final ExportProvider exportProvider) {
    File targetDir;
    String targetName;
    String defaultName = exportProvider.getViewName();

    // 1. let the user choose file or directory
    final JFileChooser chooser = getFileChooser();
    if (exportDir != null) {
        chooser.setCurrentDirectory(exportDir);
    }
    int result = chooser.showSaveDialog(WindowManager.getDefault().getRegistry().getActivated());
    if (result != JFileChooser.APPROVE_OPTION) {
        return null; // cancelled by the user
    }

    // 2. process both cases and extract file name and extension to use and set exported file type
    File file = chooser.getSelectedFile();
    String targetExt = null;
    FileFilter selectedFileFilter = chooser.getFileFilter();
    if (selectedFileFilter==null  // workaround for #227659
            ||  selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogCSVFilter())) {
        targetExt=FILE_EXTENSION_CSV;
        exportedFileType=MODE_CSV;
    } else if (selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogTXTFilter())) {
        targetExt=FILE_EXTENSION_TXT;
        exportedFileType=MODE_TXT;
    } else if (selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogBINFilter())) {
        targetExt=FILE_EXTENSION_BIN;
        exportedFileType=MODE_BIN;
    }

    if (file.isDirectory()) { // save to selected directory under default name
        exportDir = file;
        targetDir = file;
        targetName = defaultName;
    } else { // save to selected file
        targetDir = fileChooser.getCurrentDirectory();
        String fName = file.getName();

        // divide the file name into name and extension
        if (fName.endsWith("."+targetExt)) {  // NOI18N
            int idx = fName.lastIndexOf('.'); // NOI18N
            targetName = fName.substring(0, idx);
        } else {            // no extension
            targetName=fName;
        }
    }

    // 3. set type of exported file and return a newly created FileObject

    return new ExportAction.SelectedFile(targetDir, targetName, targetExt);
}