List of usage examples for javax.swing JFileChooser setCurrentDirectory
@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.") public void setCurrentDirectory(File dir)
From source file:nl.tudelft.goal.SimpleIDE.SimpleIDE.java
/** * Opens file browser panel and asks user to select a filename/directory. * * @param parentpanel//from w w w .j a va 2 s.co m * the panel to center this file browser panel on. * @param openFile * boolean that must be set to true to open a file dialog, and to * false to open a save dialog. * @param title * the title for the file browser panel. * @param mode * can be set to FILES_ONLY or DIRECTORIES_ONLY or something else * to fix selection. * @param ext * the expected extension. If the extension is not starting with * a dot, we insert a dot. Is enforced (if not null) by simply * adding when user enters a filename without any extension, or * by requesting user to change it if it is not right. If * enforceExtension = true, we throw exception when user changes * extension. If false, we allow explicit differnt extension by * user. * @param defaultName * File name that will be suggested (if not null) by the dialog. * Should be of the form defaultName###.extension. Note that if * openFile is set to true then an existing label is picked of * that form, and if openFile is set to false then a new name is * picked. * @param startdir * is the suggested start location for the browse. If this is set * to null, {@link System#getProperty(String)} is used with * String="user.home". * @param enforceExtension * is set to true if extension MUST be used. false if extension * is only suggestion and can be changed. Only applicable if * extension is not null. * @return The selected file. Adds default extension if file path does not * have file extension. * @throws GOALCommandCancelledException * if user cancels action. * @throws GOALUserError * if user makes incorrect selection. * */ public static File askFile(Component parentpanel, boolean openFile, String title, int mode, String exten, String defaultName, String startdir, boolean enforceExtension) throws GOALCommandCancelledException, GOALUserError { // insert the leading dot if necessary. String extension = (exten == null || exten.startsWith(".")) ? exten //$NON-NLS-1$ : "." + exten; //$NON-NLS-1$ /** * File name to be returned. */ File selectedFile; /** * Return state of file chooser. */ int returnState; if (startdir == null) { startdir = System.getProperty("user.home"); //$NON-NLS-1$ } try { File dir = new File(startdir); String suggestion = null; if (defaultName != null) { if (openFile) { suggestion = findExistingFilename(dir, defaultName, extension); } else { suggestion = createNewNonExistingFilename(dir, defaultName, extension); } } JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(dir); chooser.setDialogTitle(title); chooser.setFileSelectionMode(mode); if (suggestion != null) { chooser.setSelectedFile(new File(suggestion)); } if (openFile) { returnState = chooser.showOpenDialog(parentpanel); } else { returnState = chooser.showSaveDialog(parentpanel); } // TODO: handle ALL return state options + exception here if (returnState != JFileChooser.APPROVE_OPTION) { throw new GOALCommandCancelledException("user cancelled open dialog."); //$NON-NLS-1$ // FIXME: why not just return null? // That's a clean way of saying that the user did not select // any file; cancelling is not a program-breaking offence. // (and null will be returned when the user disagrees // with overwriting an existing file anyway) } selectedFile = chooser.getSelectedFile(); if (openFile && !selectedFile.exists()) { // file browsers you can select // non-existing files! throw new FileNotFoundException("File " //$NON-NLS-1$ + selectedFile.getCanonicalPath() + " does not exist."); //$NON-NLS-1$ } } catch (FileNotFoundException e) { throw new GOALUserError(e.getMessage(), e); } catch (IOException e) { throw new GOALUserError(e.getMessage(), e); } catch (HeadlessException e) { throw new GOALUserError(e.getMessage(), e); } // Check extension. String ext = FilenameUtils.getExtension(selectedFile.getName()); if (extension != null) { if (ext.isEmpty()) { selectedFile = new File(selectedFile.getAbsolutePath() + extension); } else { // Check whether extension is OK. if (enforceExtension && !("." + ext).equals(extension)) { //$NON-NLS-1$ throw new GOALUserError("The file must have extension " //$NON-NLS-1$ + extension); } } } Extension fileExtension = Extension.getFileExtension(selectedFile.getName()); if (fileExtension == null) { throw new GOALUserError("Files with extension " + ext //$NON-NLS-1$ + " are not recognized by GOAL"); //$NON-NLS-1$ } // Check whether file name already exists. if (!openFile && selectedFile != null && selectedFile.exists()) { int selection = JOptionPane.showConfirmDialog(parentpanel, "Overwrite existing file?", "Overwrite?", //$NON-NLS-1$ //$NON-NLS-2$ JOptionPane.YES_NO_OPTION); if (selection != JOptionPane.YES_OPTION) { throw new GOALCommandCancelledException("User refused overwrite of file " + selectedFile); //$NON-NLS-1$ } } return selectedFile; }
From source file:nubisave.component.graph.splitteradaption.NubisaveEditor.java
/** * create an instance of a simple graph with popup controls to * create a graph.// w w w. j av a 2 s . c o m * */ public NubisaveEditor() { // create a simple graph for the demo graph = new SortedSparseMultiGraph<NubiSaveVertex, NubiSaveEdge>(); this.layout = new StaticLayout<NubiSaveVertex, NubiSaveEdge>(graph, new Dimension(600, 600)); vv = new VisualizationViewer<NubiSaveVertex, NubiSaveEdge>(layout); dataVertexEdgeFactory = new DataVertexEdgeFactory(); storage_directory = new PropertiesUtil("nubi.properties").getProperty("storage_configuration_directory"); //Immediate Adaption to external changes int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; boolean watchSubtree = false; // try { // JNotify.addWatch(Nubisave.mainSplitter.getConfigDir(), mask, watchSubtree, new JNotifyConfigUpdater(dataVertexEdgeFactory, graph, vv)); // } catch (Exception ex) { // Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); // } vv.setBackground(Color.white); vv.getRenderContext().setEdgeStrokeTransformer(new EdgeWeightStrokeFunction<NubiSaveEdge>()); vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<NubiSaveEdge>()); vv.getRenderContext() .setVertexShapeTransformer(new BufferedImageDelegatorVertexShapeTransformer<NubiSaveVertex>()); vv.getRenderContext() .setVertexIconTransformer(new BufferedImageDelegatorVertexIconTransformer<NubiSaveVertex>()); vv.setVertexToolTipTransformer(vv.getRenderContext().getVertexLabelTransformer()); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); vv.getRenderContext().setVertexLabelTransformer(new GenericComponentLabeller<NubiSaveVertex>()); vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<NubiSaveVertex, NubiSaveEdge>()); new BufferedImageDelegatorHighlighter(vv.getPickedVertexState()); Container content = this; final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); content.add(panel); final StatefulNubiSaveComponentFactory vertexFactory = new StatefulNubiSaveComponentFactory(); Factory<? extends NubiSaveEdge> edgeFactory = new WeightedNubisaveVertexEdgeFactory(); final PluggableGraphMouse graphMouse = createPluggableGraphMouse(vv.getRenderContext(), vertexFactory, edgeFactory, dataVertexEdgeFactory); // try { // // the EditingGraphMouse will pass mouse event coordinates to the // // vertexLocations function to set the locations of the vertices as // // they are created //graphMouse.setVertexLocations(vertexLocations); // nubiSaveComponent = new NubiSaveComponent(); // nubiSaveComponent.addToGraph(vv, new java.awt.Point((int)layout.getSize().getHeight()/2,(int)layout.getSize().getWidth()/2)); // } catch (IOException ex) { // Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); // } vv.setGraphMouse(graphMouse); vv.addKeyListener(new ActionKeyAdapter(vv.getPickedVertexState(), graph)); JButton help = new JButton("Help"); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(vv, instructions); } }); addServicesToGraph(); Graph<AbstractNubisaveComponent, Object> nubisaveComponentGraph = new VertexPredicateFilter( new Predicate() { @Override public boolean evaluate(Object vertex) { return vertex instanceof AbstractNubisaveComponent; } }).transform(graph); interconnectNubisaveComponents(nubisaveComponentGraph, edgeFactory); //interconnectNubisaveComponents(); JPanel controls = new JPanel(); JButton chooseLocalComponent = new JButton("Custom Storage/Modification/Splitter Module"); chooseLocalComponent.addActionListener(new ActionListener() { /** * Create new {@link StorageService} from chosen file and set it as the next Vertex to create in {@link StatefulNubiSaveComponentFactory} */ @Override public void actionPerformed(ActionEvent ae) { CustomServiceDlg cusDlg = new CustomServiceDlg(); cusDlg.pack(); cusDlg.setLocationRelativeTo(null); cusDlg.setTitle("Module Selection"); cusDlg.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); cusDlg.setVisible(true); String module = (String) cusDlg.getItemName(); if (module != null) { module = module.split("\\.")[0]; } if (module != null) { if (cusDlg.okstatus == "True") { if (module.toLowerCase().equals("nubisave")) { StorageService newService = new StorageService(module); try { vertexFactory.setNextInstance(new NubiSaveComponent(newService)); //nubiSaveComponent.addToGraph(vv, new java.awt.Point((int)layout.getSize().getHeight()/2,(int)layout.getSize().getWidth()/2)); } catch (IOException ex) { Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); } nubisave.Nubisave.services.addNubisave(newService); } else { StorageService newService = new StorageService(module); try { vertexFactory.setNextInstance(new GenericNubiSaveComponent(newService)); } catch (IOException ex) { Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); } nubisave.Nubisave.services.add(newService); } } } else { JFileChooser customStorageserviceChooser = new javax.swing.JFileChooser(); customStorageserviceChooser.setCurrentDirectory( new java.io.File(nubisave.Nubisave.mainSplitter.getMountScriptDir())); customStorageserviceChooser.setDialogTitle("Custom Service"); customStorageserviceChooser.setFileFilter(new IniFileFilter()); int returnVal = customStorageserviceChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = customStorageserviceChooser.getSelectedFile(); if (file.getName().toLowerCase().equals("nubisave.ini")) { StorageService newService = new StorageService(file); try { vertexFactory.setNextInstance(new NubiSaveComponent(newService)); //nubiSaveComponent.addToGraph(vv, new java.awt.Point((int)layout.getSize().getHeight()/2,(int)layout.getSize().getWidth()/2)); } catch (IOException ex) { Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); } nubisave.Nubisave.services.addNubisave(newService); } else { StorageService newService = new StorageService(file); try { vertexFactory.setNextInstance(new GenericNubiSaveComponent(newService)); } catch (IOException ex) { Logger.getLogger(NubisaveEditor.class.getName()).log(Level.SEVERE, null, ex); } nubisave.Nubisave.services.add(newService); } } } } }); controls.add(chooseLocalComponent); JButton searchServiceComponent = new JButton("Storage Service Directory"); searchServiceComponent.addActionListener(new ActionListener() { /** * Create new {@link StorageService} from chosen file and set it as the next Vertex to create in {@link StatefulNubiSaveComponentFactory} */ @Override public void actionPerformed(ActionEvent ae) { AddServiceDialog addServiceDlg = new AddServiceDialog(null, true); addServiceDlg.setVisible(true); for (MatchmakerService newService : addServiceDlg.getSelectedServices()) { try { vertexFactory.setNextInstance(new GenericNubiSaveComponent(newService)); } catch (IOException ex) { Logger.getLogger(AddServiceDialog.class.getName()).log(Level.SEVERE, null, ex); } } } }); controls.add(searchServiceComponent); controls.add(help); content.add(controls, BorderLayout.SOUTH); }
From source file:nz.ac.massey.cs.gql4jung.browser.ResultBrowser.java
private void actLoadQuery() { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(".")); fc.setDialogTitle("Load query"); int returnVal = fc.showOpenDialog(this); FileFilter filter = new FileFilter() { @Override/* w w w. j a v a 2s.c om*/ public boolean accept(File f) { return f.getAbsolutePath().endsWith(".xml"); } @Override public String getDescription() { return "xml"; } }; fc.setFileFilter(filter); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); loadQuery(file); } updateActions(); updateStatus(); }
From source file:nz.ac.massey.cs.gql4jung.browser.ResultBrowser.java
private void actLoadData() { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(".")); fc.setDialogTitle("Load graph"); int returnVal = fc.showOpenDialog(this); FileFilter filter = new FileFilter() { @Override//from w w w. j a v a 2s. c o m public boolean accept(File f) { return f.getAbsolutePath().endsWith(".graphml"); } @Override public String getDescription() { return "graphml files"; } }; fc.setFileFilter(filter); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); loadData(file); } updateActions(); updateStatus(); }
From source file:org.andrewberman.sync.PDFDownloader.java
static File chooseDirectory() throws Exception { JFileChooser fc = new JFileChooser(); // fc.setDialogTitle("Choose Output Directory"); // Start in current directory fc.setCurrentDirectory(new File(".")); // Choose only directories only. fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Open chooser dialog int result = fc.showSaveDialog(new JFrame()); if (result == JFileChooser.CANCEL_OPTION) { out.println("Directory choice was canceled. Exiting..."); // System.exit(1); throw new Exception(); }// w w w.ja v a 2 s. c om File f = fc.getSelectedFile(); out.println("Chosen directory:" + f); return f; }
From source file:org.apache.cayenne.modeler.dialog.codegen.GeneratorController.java
/** * An action method that pops up a file chooser dialog to pick the * generation directory./*w ww. ja v a 2 s .c o m*/ */ public void selectOutputFolderAction() { JTextField outputFolder = ((GeneratorControllerPanel) getView()).getOutputFolder(); String currentDir = outputFolder.getText(); JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); // guess start directory if (!Util.isEmptyString(currentDir)) { chooser.setCurrentDirectory(new File(currentDir)); } else { FSPath lastDir = Application.getInstance().getFrameController().getLastDirectory(); lastDir.updateChooser(chooser); } int result = chooser.showOpenDialog(getView()); if (result == JFileChooser.APPROVE_OPTION) { File selected = chooser.getSelectedFile(); // update model String path = selected.getAbsolutePath(); outputFolder.setText(path); setOutputPath(path); } }
From source file:org.apache.cayenne.modeler.dialog.db.merge.MergerOptions.java
/** * Allows user to save generated SQL in a file. *///from w w w. ja v a 2s.co m public void storeSQLAction() { JFileChooser fc = new JFileChooser(); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setDialogTitle("Save SQL Script"); Resource projectDir = getApplication().getProject().getConfigurationResource(); if (projectDir != null) { fc.setCurrentDirectory(new File(projectDir.getURL().getPath())); } if (fc.showSaveDialog(getView()) == JFileChooser.APPROVE_OPTION) { refreshGeneratorAction(); try { File file = fc.getSelectedFile(); FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw); pw.print(textForSQL); pw.flush(); pw.close(); } catch (IOException ex) { reportError("Error Saving SQL", ex); } } }
From source file:org.docwhat.iated.ui.PreferencesDialog.java
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Please select your editor"); chooser.setCurrentDirectory(new File(getDefaultAppDirectory())); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { if (OS.isFamilyMac() && f.isDirectory() && f.getName().toLowerCase().endsWith(".app")) { return (true); }/* w ww .ja v a2 s . c om*/ return f.canExecute(); } public String getDescription() { return "Applications"; } }); int result = chooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { editorField.setText(chooser.getSelectedFile().getPath()); } }
From source file:org.domainmath.gui.MainFrame.java
/** * Creates file chooser dialog box and allows the user to select files * and importData selected files in fileTab. *//*ww w .ja v a 2s.c om*/ public void open() { JFileChooser fc = new JFileChooser(); // set current directory. if (fileTab.getTabCount() > 0) { File f = new File(fileTab.getToolTipTextAt(fileTab.getSelectedIndex())); fc.setCurrentDirectory(f.getParentFile()); } else { fc.setCurrentDirectory(new File(System.getProperty("user.dir") + File.separator + "works")); } FileNameExtensionFilter filter = new FileNameExtensionFilter("M-Files (*.m)", "m"); fc.setAcceptAllFileFilterUsed(false); fc.setFileFilter(filter); fc.setMultiSelectionEnabled(true); fc.setFileView(new ScriptFileView()); File file1[]; int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { file1 = fc.getSelectedFiles(); this.setCurrentDirFileTab(fc.getCurrentDirectory().getAbsolutePath()); for (int i = 0; i < file1.length; i++) { if (!fileNameList.contains(file1[i].getAbsolutePath())) { open(file1[i], i); } else { System.out.println(file1[i].getAbsolutePath() + " already open!"); } } } }
From source file:org.domainmath.gui.MainFrame.java
public void browse() { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(System.getProperty("user.dir") + File.separator + "works")); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setMultiSelectionEnabled(false);//from w w w . j av a2 s . c om File _file; int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { _file = fc.getSelectedFile(); setDir(_file.getAbsolutePath()); } }