Java Code Examples for javax.swing.JFileChooser.CANCEL_OPTION

The following are Jave code examples for showing how to use CANCEL_OPTION of the javax.swing.JFileChooser class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Equella   File: ImportPage.java   View Source Code Vote up 6 votes
private File getFile(int reply, JFileChooser chooser, JTextField field, File oldFile)
{
	switch( reply )
	{
		case JFileChooser.ERROR_OPTION: {
			JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Error retrieving file", "Error",
				JOptionPane.ERROR_MESSAGE);
			field.setText("");
			return null;
		}
		case JFileChooser.APPROVE_OPTION: {
			File file = chooser.getSelectedFile();
			field.setText(file.getPath());
			return file;
		}
		case JFileChooser.CANCEL_OPTION: {
			return oldFile;
		}
	}
	field.setText("");
	return null;
}
 
Example 2
Project: jaer   File: Histogram2DFilter.java   View Source Code Vote up 6 votes
final synchronized public void doLoadHistogram() {
        JFileChooser fileChooser = new JFileChooser();
        String lastFilePath = getString("lastFile", System.getProperty("user.dir") );
        // get the last folder
//            fileChooser.setFileFilter(datFileFilter);
        File f=new File(lastFilePath);
        fileChooser.setCurrentDirectory(f);
        fileChooser.setSelectedFile(f);
        int retValue = fileChooser.showOpenDialog(fileChooser);
        if (retValue == JFileChooser.CANCEL_OPTION) {
            return;
        }
        File file = fileChooser.getSelectedFile();
        putString("lastFile",file.getPath());
        loadHistogramFromFile(file);
    }
 
Example 3
Project: jaer   File: Histogram2DFilter.java   View Source Code Vote up 6 votes
synchronized public void doSaveHistogram() {
        if (histmax == 0 || histogram == null) {
            log.warning("no histogram to save");
            return;
        }
        try {
            JFileChooser fileChooser = new JFileChooser();
            String lastFilePath = getFilePath();
            if(!lastFilePath.endsWith(HISTOGRAM_FILE_NAME_EXTENSION))lastFilePath=lastFilePath+HISTOGRAM_FILE_NAME_EXTENSION;
            // get the last folder
//            fileChooser.setFileFilter(datFileFilter);
            File f=new File(lastFilePath);
            fileChooser.setCurrentDirectory(f);
            fileChooser.setSelectedFile(f);
            int retValue = fileChooser.showOpenDialog(fileChooser);
            if (retValue == JFileChooser.CANCEL_OPTION) {
                return;
            }
            File file = fileChooser.getSelectedFile();
            saveHistogramToFile(file);
        } catch (IOException e) {
            log.warning("couldn't save histogram: " + e);
        }

    }
 
Example 4
Project: geomapapp   File: ImportImageLayer.java   View Source Code Vote up 6 votes
public void importImage(MapApp mapApp) {
	JFileChooser chooser = MapApp.getFileChooser();
	for (FileFilter ff : supportedImageSources)
		chooser.setFileFilter(ff);
	chooser.setFileFilter(allSources);
	
	int c = chooser.showOpenDialog(mapApp.getFrame());
	if (c == JFileChooser.CANCEL_OPTION) return;
	
	File file = chooser.getSelectedFile();
	if (file == null) return;
	
	if (file.getName().toLowerCase().endsWith(".kml"))
		importKMZ(mapApp, file, false);
	else if (file.getName().toLowerCase().endsWith(".kmz"))
		importKMZ(mapApp, file, true);
	else
		importImage(mapApp, file);
}
 
Example 5
Project: NativeJFileChooser   File: NativeJFileChooser.java   View Source Code Vote up 5 votes
@Override
    public int showSaveDialog(Component parent) throws HeadlessException {
        if (!FX_AVAILABLE) {
            return super.showSaveDialog(parent);
        }

        final CountDownLatch latch = new CountDownLatch(1);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
//                parent.setEnabled(false);
                if (isDirectorySelectionEnabled()) {
                    currentFile = directoryChooser.showDialog(null);
                } else {
                    currentFile = fileChooser.showSaveDialog(null);
                }
                latch.countDown();
//                parent.setEnabled(true);
            }

        });
        try {
            latch.await();
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }

        if (currentFile != null) {
            return JFileChooser.APPROVE_OPTION;
        } else {
            return JFileChooser.CANCEL_OPTION;
        }
    }
 
Example 6
Project: geomapapp   File: OtherDBInputDialog.java   View Source Code Vote up 5 votes
public void loadFile(){
	type = UnknownDataSet.ASCII_FILE;
	jfc.setFileFilter(null);
	int c = jfc.showOpenDialog(this);
	if (c==JFileChooser.CANCEL_OPTION || c == JFileChooser.ERROR_OPTION) return;
	path = jfc.getSelectedFile().getPath();
	loadFile(jfc.getSelectedFile());
}
 
Example 7
Project: jmt   File: CustomDialog.java   View Source Code Vote up 5 votes
File saveFileDialog(File file) {
	FileFilter fFileFilter = new FileFilter() {
		@Override
		public boolean accept(File f) {
			return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
		}

		@Override
		public String getDescription() {
			return "Comma delimited (*.csv)";
		}
	};

	JFileChooser fc = new JFileChooser(Defaults.getWorkingPath());

	// Set filter for Java source files.
	fc.setFileFilter(fFileFilter);

	// Set to a default name for save.
	fc.setSelectedFile(file);

	// Open chooser dialog
	int result = fc.showSaveDialog(this);

	if (result == JFileChooser.CANCEL_OPTION) {
		return null;
	} else if (result == JFileChooser.APPROVE_OPTION) {
		file = fc.getSelectedFile();
		if (file.exists()) {
			int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE);
			if (response == JOptionPane.CANCEL_OPTION) {
				return null;
			}
		}
		return file;
	} else {
		return null;
	}
}
 
Example 8
Project: jmt   File: Loader.java   View Source Code Vote up 5 votes
/**
 * Shows a Load window and loads chosen model inside specified model data file
 * @param modelData data file where information should be stored. Note that <b>its type
 * must be compatible with defaultFilter chosen in the constructor</b>, otherwise a
 * ClassCastException will be thrown
 * @param parent parent component of loading window
 * @return SUCCESS on success, CANCELLED if loading is cancelled,
 * FAILURE if an error occurs and WARNING is one or more warnings are generated due to
 * format conversion
 * @throws ClassCastException if modelData is not of instance of the correct class
 * @see #getFailureMotivation getFailureMotivation()
 */
public int loadModel(Component parent) {
	warnings.clear();
	int status;
	status = this.showOpenDialog(parent);
	if (status == JFileChooser.CANCEL_OPTION) {
		return CANCELLED;
	} else if (status == JFileChooser.ERROR_OPTION) {
		failureMotivation = "Error selecting input file";
		return FAILURE;
	}

	f = dialog.getSelectedFile();

	try {
		if (defaultFilter == LOG) {

		}

	} catch (Exception e) {
		e.printStackTrace();
		failureMotivation = e.getClass().getName() + ": " + e.getMessage();
		return FAILURE;
	}
	// If no warnings were found, report success
	if (warnings.size() > 0) {
		return WARNING;
	} else {
		return SUCCESS;
	}
}
 
Example 9
Project: appinventor-extensions   File: AIMerger.java   View Source Code Vote up 5 votes
private String getFileToOpen() {
  JFileChooser projectFC = new JFileChooser();
  int validPath = projectFC.showOpenDialog(myCP);
  if (validPath == JFileChooser.ERROR_OPTION || validPath == JFileChooser.CANCEL_OPTION) {
    return null;
  } else {
    return projectFC.getSelectedFile().toString();
  }
}
 
Example 10
Project: VASSAL-src   File: SavedGameUpdaterDialog.java   View Source Code Vote up 5 votes
private void chooseSavedGames() {
  fc.setMultiSelectionEnabled(true);
  if (JFileChooser.CANCEL_OPTION != fc.showOpenDialog(this)) {
    File[] selectedFiles = fc.getSelectedFiles();
    if (selectedFiles != null) {
      savedGamesModel.clear();
      for (int i = 0; i < selectedFiles.length; i++) {
        savedGamesModel.addElement(selectedFiles[i]);
      }
    }
  }
}
 
Example 11
Project: appinventor-extensions   File: AIMerger.java   View Source Code Vote up 5 votes
private String getFileToOpen() {
  JFileChooser projectFC = new JFileChooser(browserPath);
  int validPath = projectFC.showOpenDialog(myCP);
  if (validPath == JFileChooser.ERROR_OPTION || validPath == JFileChooser.CANCEL_OPTION) {
    return null;
  } else {
    return projectFC.getSelectedFile().toString();
  }
}
 
Example 12
Project: geomapapp   File: UnknownDataSet.java   View Source Code Vote up 5 votes
public void exportASCII(String saveOption){
	//run standard checks before exporting
	if (!exportChecks(saveOption)) return;
	
	JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
	File f=new File(desc.name.replace(":", "")+".txt");
	jfc.setSelectedFile(f);
	do {
		int c = jfc.showSaveDialog(null);
		if (c==JFileChooser.CANCEL_OPTION||c==JFileChooser.ERROR_OPTION) return;
		f = jfc.getSelectedFile();
		if (f.exists()) {
			c=JOptionPane.showConfirmDialog(null, "File Already Exists\nConfirm Overwrite");
			if (c==JOptionPane.OK_OPTION) break;
			if (c==JOptionPane.CANCEL_OPTION) return;
		}
	} while (f.exists());

	try {
		BufferedWriter out = new BufferedWriter(new FileWriter(f));
		//don't include Plot column
		for (int i=1;i<dataT.getColumnCount();i++)
			out.write(dataT.getColumnName(i)+"\t");
		out.write("\n");
		
		int[] ind;
		if (saveOption.equals("selection")) {
			ind = dataT.getSelectedRows();
		} else if (saveOption.equals("plottable")) {
			ind = getPlottableRows();
		} else {
			ind = new int[dataT.getRowCount()];
			for (int i=0; i<dataT.getRowCount(); i++) ind[i] = i;
		}
			
		for (int i=0;i<ind.length;i++) {
			for (int j=1; j<dataT.getColumnCount();j++) {
				Object o = dataT.getValueAt(ind[i], j);
				if (o instanceof String && ((String)o).equals("NaN")) o = "";
				out.write(o+"\t");
			}
			out.write("\n");
		}
		out.close();
	} catch (IOException ex){

	}
}
 
Example 13
Project: GTextEditor   File: Main.java   View Source Code Vote up 5 votes
private void saveMenuActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if (editTabs.getTabCount() == 0) {
        return;
    }
    String filePath;
    if (filePaths.get(editTabs.getSelectedIndex()).equals("notSet")) {
        int result = saveChooser.showSaveDialog(this);
        if(result == JFileChooser.CANCEL_OPTION)
            return;
        if (saveChooser.getSelectedFile() == null)
            return;
        filePath = saveChooser.getSelectedFile().getPath();
        editTabs.setTitleAt(editTabs.getSelectedIndex(), saveChooser.getSelectedFile().getName());
        filePaths.set(editTabs.getSelectedIndex(), filePath);
    } else {
        filePath = filePaths.get(editTabs.getSelectedIndex());
        editTabs.setTitleAt(editTabs.getSelectedIndex(), saveChooser.getSelectedFile().getName());
    }
    javax.swing.JTextArea textComp = (javax.swing.JTextArea) editTabs.getSelectedComponent();
    String text = textComp.getText();
    text = text.replaceAll("(?!\\r)\\n", "\r\n");
    try {
        Files.write(Paths.get(filePath), text.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: geomapapp   File: LayerManager.java   View Source Code Vote up 5 votes
public static void getLayerSessionChooser() throws IOException{	
	JFileChooser sessionImport = new JFileChooser
	(System.getProperty("user.home") + "/Desktop");
	sessionImport.setDialogTitle("Import Layer Session");
	sessionImport.setAcceptAllFileFilterUsed(true);
	sessionImport.setFileFilter(new FileFilter() {
		public boolean accept(File file) {
			String fileName = file.getName().toLowerCase();
			if (fileName.endsWith(".xml")) {
				return true;
			}
			return false;
			}
		public String getDescription() {
			return "XML file (*.xml)";
		}
	});
	sessionImport.setFileSelectionMode(JFileChooser.FILES_ONLY);
	int code = sessionImport.showOpenDialog(map.getParent());
	if(code==JFileChooser.CANCEL_OPTION){
		doImport = false;
		return;
	}else if(code==JFileChooser.APPROVE_OPTION){
		File f =sessionImport.getSelectedFile();
		String fs = f.toString();
		importLayerSession(fs);
		doImport = true;
	}

}
 
Example 15
Project: geomapapp   File: Digitizer.java   View Source Code Vote up 5 votes
void saveProfile(String fmt) {
	
	JFileChooser chooser = MapApp.getFileChooser();
	String defaultFileName = list.getSelectedValue().toString().replace(" ", "_") + "." + fmt;
	chooser.setSelectedFile(new File(defaultFileName));
	int ok = chooser.showSaveDialog(map.getTopLevelAncestor());
	if( ok==JFileChooser.CANCEL_OPTION ) return;
	File file = chooser.getSelectedFile();
	if( file.exists() ) {
		ok = askOverWrite();
		if( ok==JOptionPane.CANCEL_OPTION ) return;
	}

	//get the image from the graph
	BufferedImage image = graph.getFullImage();
	Graphics g = image.getGraphics();
	graph.paint(g);

	try {
		String name = file.getName();
		int sIndex = name.lastIndexOf(".");
		String suffix = sIndex<0
			? fmt
			: name.substring( sIndex+1 );
		if( !ImageIO.getImageWritersBySuffix(suffix).hasNext())suffix = fmt;

		if ( chooser.getSelectedFile().getPath().endsWith(fmt) ) {
			ImageIO.write(image, suffix, file);
		}
		else {
			ImageIO.write(image, suffix, new File(file.getPath() + fmt) );
		}

	} catch(IOException e) {
		JOptionPane.showMessageDialog(null,
				" Save failed: "+e.getMessage(),
				" Save failed",
				 JOptionPane.ERROR_MESSAGE);
	}
}
 
Example 16
Project: geomapapp   File: Digitizer.java   View Source Code Vote up 5 votes
int askOverWrite() {
	JFileChooser chooser = MapApp.getFileChooser();
	int ok = JOptionPane.NO_OPTION;
	while( true ) {
		ok = JOptionPane.showConfirmDialog(map.getTopLevelAncestor(),
			"File exists. Overwrite?",
			"Overwrite?",
			JOptionPane.YES_NO_CANCEL_OPTION);
		if( ok!=JOptionPane.NO_OPTION) return ok;
		ok = chooser.showSaveDialog(map.getTopLevelAncestor());
		if( ok==JFileChooser.CANCEL_OPTION ) return JOptionPane.CANCEL_OPTION;
		if( !chooser.getSelectedFile().exists() ) return JOptionPane.YES_OPTION;
	}
}
 
Example 17
Project: NativeJFileChooser   File: NativeJFileChooser.java   View Source Code Vote up 4 votes
@Override
    public int showOpenDialog(Component parent) throws HeadlessException {
        if (!FX_AVAILABLE) {
            return super.showOpenDialog(parent);
        }

        final CountDownLatch latch = new CountDownLatch(1);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
//                parent.setEnabled(false);
                if (isDirectorySelectionEnabled()) {
                    currentFile = directoryChooser.showDialog(null);
                } else {
                    if (isMultiSelectionEnabled()) {
                        currentFiles = fileChooser.showOpenMultipleDialog(null);
                    } else {
                        currentFile = fileChooser.showOpenDialog(null);
                    }
                }
                latch.countDown();
//                parent.setEnabled(true);
            }

        });
        try {
            latch.await();
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }

        if (isMultiSelectionEnabled()) {
            if (currentFiles != null) {
                return JFileChooser.APPROVE_OPTION;
            } else {
                return JFileChooser.CANCEL_OPTION;
            }
        } else {
            if (currentFile != null) {
                return JFileChooser.APPROVE_OPTION;
            } else {
                return JFileChooser.CANCEL_OPTION;
            }
        }

    }
 
Example 18
Project: AgentWorkbench   File: ProjectsLoaded.java   View Source Code Vote up 4 votes
/**
 * Imports a project, which is packed in Agent.GUI project file (*.agui)
 */
public void projectImport() {
	
	String optionMsg = null;
	String optionTitle = null;
	String newLine = Application.getGlobalInfo().getNewLineSeparator(); 
	
	// --- Select a *.agui file -----------------------
	String fileEnd = Application.getGlobalInfo().getFileEndProjectZip();
	FileNameExtensionFilter filter = new FileNameExtensionFilter(Language.translate("Agent.GUI Projekt-Datei") + " (*." + fileEnd + ")", fileEnd);
	
	JFileChooser chooser = new JFileChooser();
	chooser.setFileFilter(filter);
	chooser.setCurrentDirectory(Application.getGlobalInfo().getLastSelectedFolder());
	chooser.setMultiSelectionEnabled(false);
	chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
	chooser.setAcceptAllFileFilterUsed(false);
	
	int answerChooser = chooser.showDialog(Application.getMainWindow(), Language.translate("Projekt importieren"));
	if (answerChooser==JFileChooser.CANCEL_OPTION) return;
	Application.getGlobalInfo().setLastSelectedFolder(chooser.getCurrentDirectory());
	
	File projectFile = chooser.getSelectedFile();
	if (projectFile!=null && projectFile.exists()) {

		String destFolder = Application.getGlobalInfo().getPathProjects();
		String zipFolder = projectFile.getAbsolutePath();
		
		// --- Import project file as a new project ---
		Zipper zipper = CommonComponentFactory.getNewZipper(Application.getMainWindow());
		zipper.setUnzipZipFolder(zipFolder);
		zipper.setUnzipDestinationFolder(destFolder);
		
		// --- Error-Handling -------------------------
		final String rootFolder2Extract = zipper.getRootFolder2Extract();
		String testFolder = destFolder + rootFolder2Extract;
		File testFile = new File(testFolder);
		if (testFile.exists()) {
			optionTitle = rootFolder2Extract + ": " + Language.translate("Verzeichnis bereits vorhanden!");
			optionMsg = Language.translate("Verzeichnis") + ": " + testFolder + newLine;
			optionMsg+= Language.translate("Das Verzeichnis existiert bereits. Der Import wird unterbrochen.");
			JOptionPane.showMessageDialog(Application.getMainWindow(), optionMsg, optionTitle, JOptionPane.WARNING_MESSAGE);
			return;
		}
		
		// --- Define task after the unzip action -----
		Runnable afterJobTask = new Runnable() {
			@Override
			public void run() {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						Application.getProjectsLoaded().add(rootFolder2Extract);
					}
				});
			}
		};
		zipper.setAfterJobTask(afterJobTask);
		
		// --- Finally unzip --------------------------
		zipper.doUnzipFolder();
		zipper = null;
		
	}		
	
}
 
Example 19
Project: gate-core   File: MainFrame.java   View Source Code Vote up 4 votes
@Override
public void actionPerformed(ActionEvent e) {
  Runnable runnable = new Runnable() {
    @Override
    public void run() {
      fileChooser.setDialogTitle("Please select a directory which contains "
        + "the documents to be evaluated");
      fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter());
      fileChooser.setResource(CorpusBenchmarkTool.class.getName());
      int state = fileChooser.showOpenDialog(MainFrame.this);
      File startDir = fileChooser.getSelectedFile();
      if(state == JFileChooser.CANCEL_OPTION || startDir == null) return;

      fileChooser.setDialogTitle(
        "Please select the application that you want to run");
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setResource(
        CorpusBenchmarkTool.class.getName() + ".application");
      state = fileChooser.showOpenDialog(MainFrame.this);
      File testApp = fileChooser.getSelectedFile();
      if(state == JFileChooser.CANCEL_OPTION || testApp == null) return;

      // first create the tool and set its parameters
      CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
      theTool.setStartDirectory(startDir);
      theTool.setApplicationFile(testApp);
      theTool.setVerboseMode(verboseModeItem.isSelected());

      Out.prln("Please wait while GATE tools are initialised.");
      // initialise the tool
      theTool.init();
      // and execute it
      theTool.execute();
      theTool.printStatistics();

      Out.prln("<BR>Overall average precision: "
        + theTool.getPrecisionAverage());
      Out.prln("<BR>Overall average recall: " + theTool.getRecallAverage());
      Out.prln("<BR>Overall average fMeasure : "
        + theTool.getFMeasureAverage());
      Out.prln("<BR>Finished!");
      theTool.unloadPRs();
    }
  };
  Thread thread =
    new Thread(Thread.currentThread().getThreadGroup(), runnable,
      "NewCorpusEvalAction");
  thread.setPriority(Thread.MIN_PRIORITY);
  thread.start();
}
 
Example 20
Project: gate-core   File: MainFrame.java   View Source Code Vote up 4 votes
@Override
public void actionPerformed(ActionEvent e) {
  Runnable runnable = new Runnable() {
    @Override
    public void run() {
      fileChooser.setDialogTitle("Please select a directory which contains "
        + "the documents to be evaluated");
      fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter());
      fileChooser.setResource(CorpusBenchmarkTool.class.getName());
      int state = fileChooser.showOpenDialog(MainFrame.this);
      File startDir = fileChooser.getSelectedFile();
      if(state == JFileChooser.CANCEL_OPTION || startDir == null) return;

      // first create the tool and set its parameters
      CorpusBenchmarkTool theTool = new CorpusBenchmarkTool();
      theTool.setStartDirectory(startDir);
      theTool.setMarkedStored(true);
      theTool.setVerboseMode(verboseModeItem.isSelected());
      // theTool.setMarkedDS(
      // MainFrame.this.datastoreModeCorpusEvalToolAction.isDatastoreMode());

      Out
        .prln("Evaluating human-marked documents against pre-stored results.");
      // initialise the tool
      theTool.init();
      // and execute it
      theTool.execute();
      theTool.printStatistics();

      Out.prln("<BR>Overall average precision: "
        + theTool.getPrecisionAverage());
      Out.prln("<BR>Overall average recall: " + theTool.getRecallAverage());
      Out.prln("<BR>Overall average fMeasure : "
        + theTool.getFMeasureAverage());
      Out.prln("<BR>Finished!");
      theTool.unloadPRs();
    }
  };
  Thread thread =
    new Thread(Thread.currentThread().getThreadGroup(), runnable,
      "StoredMarkedCorpusEvalAction");
  thread.setPriority(Thread.MIN_PRIORITY);
  thread.start();
}