List of usage examples for javax.swing JFileChooser getSelectedFile
public File getSelectedFile()
From source file:au.org.ala.delta.intkey.ui.UIUtils.java
/** * Prompts for a file using the file chooser dialog * /*from w w w.j a v a 2 s . c o m*/ * @param fileExtensions * Accepted file extensions - must be null if filePrefixes is * non-null * @param filePrefixes * Accepted file prefixes - must be null if fileExtensions is * non-null * @param description * Description of the acceptable files * @param createFileIfNonExistant * if true, the file will be created if it does not exist. Also, * the system's "save" will be used instead of the "open" dialog. * @param startBrowseDirectory * The directory that the file chooser should start in * @param parent * parent component for the file chooser * @return the selected file, or null if no file was selected. * @throws IOException */ public static File promptForFile(List<String> fileExtensions, List<String> filePrefixes, final String description, boolean createFileIfNonExistant, File startBrowseDirectory, Component parent) throws IOException { if (fileExtensions != null && filePrefixes != null) { throw new IllegalArgumentException( "Only one of the file extensions or file prefixes should be non-null"); } JFileChooser chooser = new JFileChooser(startBrowseDirectory); FileFilter filter; if (fileExtensions != null) { String[] extensionsArray = new String[fileExtensions.size()]; fileExtensions.toArray(extensionsArray); filter = new FileNameExtensionFilter(description, extensionsArray); } else { final String[] prefixesArray = new String[filePrefixes.size()]; filePrefixes.toArray(prefixesArray); filter = new FileFilter() { @Override public String getDescription() { return description; } @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } else { return StringUtils.startsWithAny(f.getName(), prefixesArray); } } }; } chooser.setFileFilter(filter); int returnVal; if (createFileIfNonExistant) { returnVal = chooser.showSaveDialog(parent); } else { returnVal = chooser.showOpenDialog(parent); } if (returnVal == JFileChooser.APPROVE_OPTION) { if (createFileIfNonExistant) { File file = chooser.getSelectedFile(); if (!file.exists()) { // if only one file extension was supplied and the filename // does // not end with this extension, add it before // creating the file if (fileExtensions.size() == 1) { String extension = fileExtensions.get(0); String filePath = chooser.getSelectedFile().getAbsolutePath(); if (!filePath.endsWith(extension)) { file = new File(filePath + "." + extension); } } file.createNewFile(); } return file; } else { return chooser.getSelectedFile(); } } else { return null; } }
From source file:EnhancedFileTester.java
public EnhancedFileTester() { JButton jb = new JButton("Open File Viewer"); add(jb);//from w ww. j av a2 s. co m ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser("."); FileFilter type1 = new ExtensionFilter("Java source", ".java"); FileFilter type2 = new ExtensionFilter("Image files", new String[] { ".jpg", ".gif", "jpeg", "xbm" }); FileFilter type3 = new ExtensionFilter("HTML files", new String[] { ".htm", ".html" }); chooser.addChoosableFileFilter(type1); chooser.addChoosableFileFilter(type2); chooser.addChoosableFileFilter(type3); chooser.setFileFilter(type2); // Initial filter setting FileView view = new IconView(); chooser.setFileView(view); int status = chooser.showOpenDialog(EnhancedFileTester.this); if (status == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); System.out.println(f); } } }; jb.addActionListener(listener); }
From source file:com.ga.forms.DailyLogUI.java
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed System.out.print(/*from ww w . jav a2s.co m*/ "REGEX: " + monthCombo.getSelectedItem().toString() + "-" + yearCombo.getSelectedItem().toString()); JFrame fileChooserFrame = new JFrame(); JFileChooser saveFileDialog = new JFileChooser(); FileNameExtensionFilter fileExtentionFilter = new FileNameExtensionFilter("Comma Seperated Values (*.csv)", "csv"); saveFileDialog.setFileFilter(fileExtentionFilter); int saveFileDialogStatus = saveFileDialog.showSaveDialog(fileChooserFrame); if (saveFileDialogStatus == JFileChooser.APPROVE_OPTION) { String fileSaveDetails = saveFileDialog.getSelectedFile().toString(); args = new HashMap(); HashMap regex = new HashMap(); regex.put("$regex", monthCombo.getSelectedItem().toString() + "-" + yearCombo.getSelectedItem().toString()); args.put("date", regex); DailyLogRecord record = new DailyLogRecord(); ArrayList logs = record.retrieveRecord(args); String[] columnNames = new String[] { "Date", "Day", "In", "Out", "Break", "Duration", "Under-Time", "Over-Time" }; ArrayList data = null; if (!logs.isEmpty()) { data = new ArrayList(); data.add(String.join(",", columnNames)); for (int logIndex = 0; logIndex < logs.size(); logIndex++) { JSONObject logJSONOBject = new JSONObject((Map) logs.get(logIndex)); String csvRecord = logJSONOBject.get("date").toString() + "," + logJSONOBject.get("day").toString() + "," + logJSONOBject.get("check-in").toString() + "," + logJSONOBject.get("check-out").toString() + "," + logJSONOBject.get("break").toString() + "," + logJSONOBject.get("duration").toString() + "," + logJSONOBject.get("under-time").toString() + "," + logJSONOBject.get("over-time").toString(); data.add(csvRecord); } } DailyLogCSVExport csvExporter = new DailyLogCSVExport(); csvExporter.save(data, fileSaveDetails); } }
From source file:com.emental.mindraider.ui.dialogs.AttachmentJDialog.java
/** * Concetructor.//from w w w. jav a 2 s . c o m * * @param noteResource * The concept resource. * @param dragAndDropReference * The drag'n'drop reference. */ public AttachmentJDialog(ConceptResource conceptResource, DragAndDropReference dragAndDropReference) { super(Messages.getString("AttachmentJDialog.title")); this.conceptResource = conceptResource; getContentPane().setLayout(new BorderLayout()); JPanel p, pp; p = new JPanel(); p.setLayout(new BorderLayout()); JLabel intro = new JLabel("<html> " + Messages.getString("AttachmentJDialog.introduction") + " <br><br></html>"); p.add(intro, BorderLayout.NORTH); p.add(new JLabel("<html> " + Messages.getString("AttachmentJDialog.description") + "</html>"), BorderLayout.CENTER); description = new JTextField(38); pp = new JPanel(new FlowLayout(FlowLayout.LEFT)); pp.add(description); p.add(pp, BorderLayout.SOUTH); getContentPane().add(p, BorderLayout.NORTH); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.setBorder(new TitledBorder(Messages.getString("AttachmentJDialog.resource"))); ButtonGroup attachType = new ButtonGroup(); JPanel webPanel = new JPanel(); webPanel.setLayout(new BorderLayout()); webType = new JRadioButton(Messages.getString("AttachmentJDialog.web")); webType.setActionCommand(WEB); webType.addActionListener(this); webType.setSelected(true); attachType.add(webType); webPanel.add(webType, BorderLayout.NORTH); urlTextField = new JTextField("http://", 35); urlTextField.selectAll(); urlTextField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) { attach(); } } public void keyReleased(KeyEvent keyEvent) { } public void keyTyped(KeyEvent keyEvent) { } }); p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.LEFT)); p.add(new JLabel(" ")); p.add(urlTextField); webPanel.add(p, BorderLayout.SOUTH); mainPanel.add(webPanel, BorderLayout.NORTH); JPanel localPanel = new JPanel(); localPanel.setLayout(new BorderLayout()); JRadioButton localType = new JRadioButton(Messages.getString("AttachmentJDialog.local")); localType.setActionCommand(LOCAL); localType.addActionListener(this); localPanel.add(localType, BorderLayout.NORTH); pathTextField = new JTextField(35); pathTextField.setEnabled(false); browseButton = new JButton(Messages.getString("AttachmentJDialog.browse")); browseButton.setToolTipText(Messages.getString("AttachmentJDialog.browseTip")); browseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.setApproveButtonText(Messages.getString("AttachmentJDialog.attach")); fc.setControlButtonsAreShown(true); fc.setDialogTitle(Messages.getString("AttachmentJDialog.chooseAttachment")); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int returnVal = fc.showOpenDialog(AttachmentJDialog.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); pathTextField.setText(file.toString()); } } }); browseButton.setEnabled(false); pp = new JPanel(); pp.setLayout(new BorderLayout()); p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.LEFT)); p.add(new JLabel(" ")); pp.add(p, BorderLayout.NORTH); p.add(pathTextField); p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.RIGHT)); p.add(browseButton); pp.add(p, BorderLayout.SOUTH); localPanel.add(pp, BorderLayout.SOUTH); attachType.add(localType); mainPanel.add(localPanel, BorderLayout.SOUTH); getContentPane().add(mainPanel, BorderLayout.CENTER); // buttons p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.CENTER)); JButton addButton = new JButton(Messages.getString("AttachmentJDialog.attach")); p.add(addButton); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { attach(); } }); JButton cancelButton = new JButton(Messages.getString("AttachmentJDialog.cancel")); p.add(cancelButton); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AttachmentJDialog.this.dispose(); } }); getContentPane().add(p, BorderLayout.SOUTH); /* * drag and drop initialization */ if (dragAndDropReference != null) { if (dragAndDropReference.getType() == DragAndDropReference.BROWSER_LINK) { urlTextField.setText(dragAndDropReference.getReference()); localType.setSelected(false); webType.setSelected(true); enableWebTypeButtons(); } else { pathTextField.setText(dragAndDropReference.getReference()); localType.setSelected(true); webType.setSelected(false); enableLocalTypeButtons(); } description.setText(dragAndDropReference.getTitle()); } pack(); Gfx.centerAndShowWindow(this); }
From source file:jpad.MainEditor.java
public void saveAs() { if (_isOSX || ostype == ostype.Linux || ostype == ostype.Other) { saveAs_OSX_Nix();//from w ww . ja v a2 s . c om saveFile(curFile); } else /* Windows */ { JFileChooser fc = new JFileChooser(); if (curFile != null) fc.setSelectedFile(new File(curFile)); else fc.setSelectedFile(new File("Untitled.txt")); fc.setDialogTitle("Save Text File"); fc.setFileFilter(new FileNameExtensionFilter("Plain Text Files", "txt")); int returnval = fc.showSaveDialog(this); if (returnval == 0) { curFile = fc.getSelectedFile().getAbsolutePath(); if (!curFile.endsWith(".txt")) curFile = curFile + ".txt"; hasChanges = false; hasSavedToFile = true; saveFile(curFile); } } }
From source file:com.signalcollect.sna.visualization.SignalCollectSNATopComponent.java
/** * Displays a file chooser when clicking on the "Choose File" button The * chosen file is then used for a new gephi project * * @param evt/*from w ww . j av a2s . co m*/ */ private void fileChooserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileChooserButtonActionPerformed FileNameExtensionFilter filter = new FileNameExtensionFilter("Graph Files", "gml"); JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(filter); int result = chooser.showOpenDialog(this); if (chooser.getSelectedFile() != null && result == JFileChooser.APPROVE_OPTION) { fileName = chooser.getSelectedFile().getAbsolutePath(); jTextArea1.setText(fileName); distributionFrame = new JFrame(); try { ProjectController pc = Lookup.getDefault().lookup(ProjectController.class); pc.newProject(); ImportController ic = Lookup.getDefault().lookup(ImportController.class); File file = new File(fileName); Container c = ic.importFile(file); ic.process(c, new DefaultProcessor(), pc.newWorkspace(pc.getCurrentProject())); propertyContentDisplay.setText(""); } catch (Exception exception) { messageFrame = new JFrame(); exception.printStackTrace(); JOptionPane.showMessageDialog(messageFrame, "Error while creating graph (" + exception.getCause() + "), please choose a valid .gml-File", "Signal/Collect Error", JOptionPane.ERROR_MESSAGE); } } }
From source file:MyFormApp.java
private void AddbuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AddbuttonMouseClicked // TODO add your handling code here: //? ?//from w ww .ja v a 2s. co m JFileChooser fileChooser = new JFileChooser(); //? fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));//?pdf fileChooser.setAcceptAllFileFilterUsed(false); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) {//???? File selectedFile = fileChooser.getSelectedFile(); try { pdfToimage(selectedFile); //??? } catch (IOException ex) { Logger.getLogger(MyFormApp.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(selectedFile.getName()); //?? File source = new File("" + selectedFile); File dest = new File(PATH + selectedFile.getName()); //copy file conventional way using Stream long start = System.nanoTime(); //copy files using apache commons io start = System.nanoTime(); int a = i + 1; String imagename = FilenameUtils.removeExtension(selectedFile.getName()); model.addElement(new Book(selectedFile.getName(), "" + a, imagename, PATH)); //list i = i + 1; jList2.setModel(model); jList2.setCellRenderer(new BookRenderer()); try { copyFileUsingApacheCommonsIO(source, dest); //? } catch (IOException ex) { Logger.getLogger(MyFormApp.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Time taken by Apache Commons IO Copy = " + (System.nanoTime() - start)); } }
From source file:de.ist.clonto.Ontogui.java
private void backupOntologyButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_backupOntologyButtonActionPerformed JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new File(System.getProperty("user.dir"))); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try {//from w w w . jav a2 s.com FileUtils.cleanDirectory(fc.getSelectedFile()); FileUtils.copyDirectory(ontoPath.toFile(), fc.getSelectedFile()); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Loading ontology failed"); } JOptionPane.showMessageDialog(this, "Created Backup files!"); } else { JOptionPane.showMessageDialog(this, "Loading ontology failed"); } }
From source file:com.genericworkflownodes.knime.nodes.io.OutputFileNodeDialog.java
/** * New pane for configuring MimeFileExporter node dialog. *///from w ww .ja v a2 s .co m public OutputFileNodeDialog(final String settingsName) { this.settingsName = settingsName; dialogPanel = new JPanel(); componentContainer = new JPanel(); textField = new JTextField(); textField.setPreferredSize(new Dimension(300, textField.getPreferredSize().height)); searchButton = new JButton("Browse"); searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFileChooser jfc = new JFileChooser(); if (!"".equals(textField.getText().trim()) && new File(textField.getText().trim()).getParent() != null) { jfc.setCurrentDirectory(new File(textField.getText().trim()).getParentFile()); } jfc.setAcceptAllFileFilterUsed(false); jfc.setFileFilter(extensionFilter); // int returnVal = jfc.showSaveDialog(dialogPanel); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = jfc.showDialog(dialogPanel, "Select output file"); if (returnVal == JFileChooser.APPROVE_OPTION) { // validate extension if (!extensionFilter.accept(jfc.getSelectedFile())) { String message = "The selected output file has an invalid file extension.\n"; if (extensionFilter.getExtensions().length == 1) { message += "Please choose a file with extension: " + extensionFilter.getExtensions()[0]; } else { message += "Please choose a file with on of the following extensions: "; message += StringUtils.join(extensionFilter.getExtensions(), ", "); } JOptionPane.showMessageDialog(getPanel(), message, "Selected Output File is invalid.", JOptionPane.WARNING_MESSAGE); } textField.setText(jfc.getSelectedFile().getAbsolutePath()); } } }); setLayout(); addComponents(); addTab("Choose File", dialogPanel); }
From source file:com.mycompany.zad1.MainWindow.java
private int[][] loadMask() { JFileChooser chooser = new JFileChooser(); int dialogResult = chooser.showOpenDialog(this); ArrayList<String> fileLines = new ArrayList<>(); if (dialogResult == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try {/*from www . j av a 2s .com*/ FileReader fileReader = new FileReader(); fileLines = fileReader.readMask(file); } catch (Exception ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } } Parser parser = new Parser(); int[][] mask = parser.parseMask(fileLines); return mask; }