List of usage examples for javax.swing JFileChooser setFileFilter
@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.") public void setFileFilter(FileFilter filter)
From source file:net.sf.jabref.openoffice.AutoDetectPaths.java
private boolean autoDetectPaths() { if (OS.WINDOWS) { List<File> progFiles = findProgramFilesDir(); File sOffice = null;//from ww w . j a v a2s.co m List<File> sofficeFiles = new ArrayList<>(); for (File dir : progFiles) { if (fileSearchCancelled) { return false; } sOffice = findFileDir(dir, "soffice.exe"); if (sOffice != null) { sofficeFiles.add(sOffice); } } if (sOffice == null) { JOptionPane.showMessageDialog(parent, Localization.lang( "Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."), Localization.lang("Could not find OpenOffice/LibreOffice installation"), JOptionPane.INFORMATION_MESSAGE); JFileChooser jfc = new JFileChooser(new File("C:\\")); jfc.setDialogType(JFileChooser.OPEN_DIALOG); jfc.setFileFilter(new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } @Override public String getDescription() { return Localization.lang("Directories"); } }); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.showOpenDialog(parent); if (jfc.getSelectedFile() != null) { sOffice = jfc.getSelectedFile(); } } if (sOffice == null) { return false; } if (sofficeFiles.size() > 1) { // More than one file found DefaultListModel<File> mod = new DefaultListModel<>(); for (File tmpfile : sofficeFiles) { mod.addElement(tmpfile); } JList<File> fileList = new JList<>(mod); fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fileList.setSelectedIndex(0); FormBuilder b = FormBuilder.create() .layout(new FormLayout("left:pref", "pref, 2dlu, pref, 4dlu, pref")); b.add(Localization.lang("Found more than one OpenOffice/LibreOffice executable.")).xy(1, 1); b.add(Localization.lang("Please choose which one to connect to:")).xy(1, 3); b.add(fileList).xy(1, 5); int answer = JOptionPane.showConfirmDialog(null, b.getPanel(), Localization.lang("Choose OpenOffice/LibreOffice executable"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.CANCEL_OPTION) { return false; } else { sOffice = fileList.getSelectedValue(); } } else { sOffice = sofficeFiles.get(0); } return setupPreferencesForOO(sOffice.getParentFile(), sOffice, "soffice.exe"); } else if (OS.OS_X) { File rootDir = new File("/Applications"); File[] files = rootDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory() && ("OpenOffice.org.app".equals(file.getName()) || "LibreOffice.app".equals(file.getName()))) { rootDir = file; break; } } } File sOffice = findFileDir(rootDir, SOFFICE_BIN); if (fileSearchCancelled) { return false; } if (sOffice == null) { return false; } else { return setupPreferencesForOO(rootDir, sOffice, SOFFICE_BIN); } } else { // Linux: String usrRoot = "/usr/lib"; File inUsr = findFileDir(new File(usrRoot), SOFFICE); if (fileSearchCancelled) { return false; } if (inUsr == null) { inUsr = findFileDir(new File("/usr/lib64"), SOFFICE); if (inUsr != null) { usrRoot = "/usr/lib64"; } } if (fileSearchCancelled) { return false; } File inOpt = findFileDir(new File("/opt"), SOFFICE); if (fileSearchCancelled) { return false; } if ((inUsr != null) && (inOpt == null)) { return setupPreferencesForOO(usrRoot, inUsr, SOFFICE_BIN); } else if (inOpt != null) { if (inUsr == null) { return setupPreferencesForOO("/opt", inOpt, SOFFICE_BIN); } else { // Found both JRadioButton optRB = new JRadioButton(inOpt.getPath(), true); JRadioButton usrRB = new JRadioButton(inUsr.getPath(), false); ButtonGroup bg = new ButtonGroup(); bg.add(optRB); bg.add(usrRB); FormBuilder b = FormBuilder.create() .layout(new FormLayout("left:pref", "pref, 2dlu, pref, 2dlu, pref ")); b.add(Localization.lang( "Found more than one OpenOffice/LibreOffice executable. Please choose which one to connect to:")) .xy(1, 1); b.add(optRB).xy(1, 3); b.add(usrRB).xy(1, 5); int answer = JOptionPane.showConfirmDialog(null, b.getPanel(), Localization.lang("Choose OpenOffice/LibreOffice executable"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.CANCEL_OPTION) { return false; } if (optRB.isSelected()) { return setupPreferencesForOO("/opt", inOpt, SOFFICE_BIN); } else { return setupPreferencesForOO(usrRoot, inUsr, SOFFICE_BIN); } } } } return false; }
From source file:Compare.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String userDir = System.getProperty("user.home"); JFileChooser folder = new JFileChooser(userDir + "/Desktop"); folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); folder.setFileSelectionMode(JFileChooser.FILES_ONLY); FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files (*.xls)", "xls"); folder.setFileFilter(xmlfilter); int returnvalue = folder.showSaveDialog(this); File myfolder = null;/* ww w .j a v a2s. com*/ if (returnvalue == JFileChooser.APPROVE_OPTION) { myfolder = folder.getSelectedFile(); // System.out.println(myfolder); } if (myfolder != null) { JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder); } listofFiles(myfolder); sortByName(); DefaultTableModel model = (DefaultTableModel) FileDetails.getModel(); int count = 1; for (Files filename : filenames1) { String size = Long.toString(filename.Filesize) + "Bytes"; model.addRow(new Object[] { count++, filename.Filename, size, filename.FileLocation }); } }
From source file:Compare.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String userDir = System.getProperty("user.home"); JFileChooser folder = new JFileChooser(userDir + "/Desktop"); folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); folder.setFileSelectionMode(JFileChooser.FILES_ONLY); FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files (*.xls)", "xls"); folder.setFileFilter(xmlfilter); int returnvalue = folder.showSaveDialog(this); File myfolder = null;/*from w w w. j a v a2 s. com*/ if (returnvalue == JFileChooser.APPROVE_OPTION) { myfolder = folder.getSelectedFile(); // System.out.println(myfolder); } if (myfolder != null) { JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder); listofFiles1(myfolder); sortByName1(); } DefaultTableModel model = (DefaultTableModel) FileDetails1.getModel(); int count = 1; System.out.println(filenames2.size()); for (Files filename : filenames2) { String size = Long.toString(filename.Filesize) + "Bytes"; model.addRow(new Object[] { count++, filename.Filename, size, filename.FileLocation }); } }
From source file:jpad.MainEditor.java
public void openFile() { if (_isOSX || ostype == ostype.Linux || ostype == ostype.Other) { openFile_OSX_Nix();/*from w w w. j a va 2s. c o m*/ } else { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Open a Text File"); fc.setFileFilter(new FileNameExtensionFilter("Plain Text Files", "txt")); int returnval = fc.showOpenDialog(this); if (returnval == 0) { hasSavedToFile = true; hasChanges = false; curFile = fc.getSelectedFile().getAbsolutePath(); try (FileInputStream stream = new FileInputStream(curFile)) { String file = IOUtils.toString(stream); mainTextArea.setText(file); this.setTitle(String.format("JPad - %s", curFile)); } catch (IOException ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } }
From source file:filterviewplugin.FilterViewSettingsTab.java
private void chooseIcon(final String filterName) { String iconPath = mIcons.get(filterName); JFileChooser chooser = new JFileChooser( iconPath == null ? new File("") : (new File(iconPath)).getParentFile()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); String msg = mLocalizer.msg("iconFiles", "Icon Files ({0})", "*.png,*.jpg, *.gif"); String[] extArr = { ".png", ".jpg", ".gif" }; chooser.setFileFilter(new ExtensionFileFilter(extArr, msg)); chooser.setDialogTitle(mLocalizer.msg("chooseIcon", "Choose icon for '{0}'", filterName)); Window w = UiUtilities.getLastModalChildOf(FilterViewPlugin.getInstance().getSuperFrame()); if (chooser.showDialog(w, Localizer.getLocalization(Localizer.I18N_SELECT)) == JFileChooser.APPROVE_OPTION) { if (chooser.getSelectedFile() != null) { File dir = new File(FilterViewSettings.getIconDirectoryName()); if (!dir.isDirectory()) { dir.mkdir();/*from w w w.j a v a 2 s . com*/ } String ext = chooser.getSelectedFile().getName(); ext = ext.substring(ext.lastIndexOf('.')); Icon icon = FilterViewPlugin.getInstance().getIcon(chooser.getSelectedFile().getAbsolutePath()); if (icon.getIconWidth() > MAX_ICON_WIDTH || icon.getIconHeight() > MAX_ICON_HEIGHT) { JOptionPane.showMessageDialog(w, mLocalizer.msg("iconSize", "The icon size must be at most {0}x{1}.", MAX_ICON_WIDTH, MAX_ICON_HEIGHT)); return; } try { IOUtilities.copy(chooser.getSelectedFile(), new File(dir, filterName + ext)); } catch (IOException e1) { e1.printStackTrace(); } mIcons.put(filterName, filterName + ext); mFilterList.updateUI(); } } }
From source file:com.socrata.datasync.ui.MetadataJobTab.java
public void saveJob() { populateJobFromFields();/* w w w . j a v a 2 s .c om*/ // TODO If an existing file was selected WARN user of overwriting // if first time saving this job: Open dialog box to select "Save as..." location // otherwise save to existing file boolean updateJobCommandTextField = false; String selectedJobFileLocation = jobFileLocation; if (selectedJobFileLocation.equals("")) { JFileChooser savedJobFileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( JOB_FILE_NAME + " (*." + JOB_FILE_EXTENSION + ")", JOB_FILE_EXTENSION); savedJobFileChooser.setFileFilter(filter); int returnVal = savedJobFileChooser.showSaveDialog(mainFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = savedJobFileChooser.getSelectedFile(); selectedJobFileLocation = file.getAbsolutePath(); if (!selectedJobFileLocation.endsWith("." + JOB_FILE_EXTENSION)) { selectedJobFileLocation += "." + JOB_FILE_EXTENSION; } jobFileLocation = selectedJobFileLocation; metadataJob.setPathToSavedFile(selectedJobFileLocation); jobTabTitleLabel.setText(metadataJob.getJobFilename()); updateJobCommandTextField = true; } } // actually save the job file (may overwrite) try { metadataJob.writeToFile(selectedJobFileLocation); // Update job tab title label jobTabTitleLabel.setText(metadataJob.getJobFilename()); // Update the textfield with new command if (updateJobCommandTextField) { String runJobCommand = Utils.getRunJobCommand(metadataJob.getPathToSavedFile()); runCommandTextField.setText(runJobCommand); } } catch (IOException e) { JOptionPane.showMessageDialog(mainFrame, "Error saving " + selectedJobFileLocation + ": " + e.getMessage()); } }
From source file:org.jax.maanova.plot.SaveChartAction.java
/** * {@inheritDoc}//from www .j av a 2 s. c om */ public void actionPerformed(ActionEvent e) { JFreeChart myChart = this.chart; Dimension mySize = this.size; if (myChart == null || mySize == null) { LOG.severe("Failed to save graph image because of a null value"); MessageDialogUtilities.errorLater(Maanova.getInstance().getApplicationFrame(), "Internal error: Failed to save graph image.", "Image Save Failed"); } else { // use the remembered starting dir MaanovaApplicationConfigurationManager configurationManager = MaanovaApplicationConfigurationManager .getInstance(); JMaanovaApplicationState applicationState = configurationManager.getApplicationState(); FileType rememberedJaxbImageDir = applicationState.getRecentImageExportDirectory(); File rememberedImageDir = null; if (rememberedJaxbImageDir != null && rememberedJaxbImageDir.getFileName() != null) { rememberedImageDir = new File(rememberedJaxbImageDir.getFileName()); } // select the image file to save JFileChooser fileChooser = new JFileChooser(rememberedImageDir); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setApproveButtonText("Save Graph"); fileChooser.setDialogTitle("Save Graph as Image"); fileChooser.setMultiSelectionEnabled(false); fileChooser.addChoosableFileFilter(PngFileFilter.getInstance()); fileChooser.setFileFilter(PngFileFilter.getInstance()); int response = fileChooser.showSaveDialog(Maanova.getInstance().getApplicationFrame()); if (response == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); // tack on the extension if there isn't one // already if (!PngFileFilter.getInstance().accept(selectedFile)) { String newFileName = selectedFile.getName() + "." + PngFileFilter.PNG_EXTENSION; selectedFile = new File(selectedFile.getParentFile(), newFileName); } if (selectedFile.exists()) { // ask the user if they're sure they want to overwrite String message = "Exporting the graph image to " + selectedFile.getAbsolutePath() + " will overwrite an " + " existing file. Would you like to continue anyway?"; if (LOG.isLoggable(Level.FINE)) { LOG.fine(message); } boolean overwriteOk = MessageDialogUtilities .confirmOverwrite(Maanova.getInstance().getApplicationFrame(), selectedFile); if (!overwriteOk) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("overwrite canceled"); } return; } } try { ChartUtilities.saveChartAsPNG(selectedFile, myChart, mySize.width, mySize.height); File parentDir = selectedFile.getParentFile(); if (parentDir != null) { // update the "recent image directory" ObjectFactory objectFactory = new ObjectFactory(); FileType latestJaxbImageDir = objectFactory.createFileType(); latestJaxbImageDir.setFileName(parentDir.getAbsolutePath()); applicationState.setRecentImageExportDirectory(latestJaxbImageDir); } } catch (Exception ex) { LOG.log(Level.SEVERE, "failed to save graph image", ex); } } } }
From source file:DOMTreeTest.java
/** * Open a file and load the document. *//*ww w . j a v a 2 s . c o m*/ public void openFile() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml"); } public String getDescription() { return "XML files"; } }); int r = chooser.showOpenDialog(this); if (r != JFileChooser.APPROVE_OPTION) return; final File file = chooser.getSelectedFile(); new SwingWorker<Document, Void>() { protected Document doInBackground() throws Exception { if (builder == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); } return builder.parse(file); } protected void done() { try { Document doc = get(); JTree tree = new JTree(new DOMTreeModel(doc)); tree.setCellRenderer(new DOMTreeCellRenderer()); setContentPane(new JScrollPane(tree)); validate(); } catch (Exception e) { JOptionPane.showMessageDialog(DOMTreeFrame.this, e); } } }.execute(); }
From source file:EnhancedFileTester.java
public EnhancedFileTester() { JButton jb = new JButton("Open File Viewer"); add(jb);/*from www .j a v a 2s . com*/ 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.intuit.tank.tools.script.ScriptFilterRunner.java
/** * @return/*from www. j av a2 s .co m*/ */ private Component createTopPanel() { JPanel topPanel = new JPanel(new GridBagLayout()); List<ConfiguredLanguage> configuredLanguages = ConfiguredLanguage.getConfiguredLanguages(); languageSelector = new JComboBox(configuredLanguages.toArray()); languageSelector.setSelectedIndex(0); languageSelector.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { setSyntaxStyle(); } }); currentFileLabel = new JLabel(); final JFileChooser jFileChooser = new JFileChooser(); jFileChooser.setFileFilter(new FileFilter() { @Override public String getDescription() { return "Tank XML Files"; } @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith("_ts.xml"); } }); JButton button = new JButton("Select File..."); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int showOpenDialog = jFileChooser.showOpenDialog(ScriptFilterRunner.this); if (showOpenDialog == JFileChooser.APPROVE_OPTION) { loadTSXml(jFileChooser.getSelectedFile()); } } }); xmlViewDialog = new XMlViewDialog(this); xmlViewDialog.setSize(new Dimension(800, 500)); showXmlBT = new JButton("Show XML"); showXmlBT.setEnabled(false); showXmlBT.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { displayXml(); } }); saveBT = new JButton("Save XML"); saveBT.setEnabled(false); saveBT.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveXml(); } }); JPanel xmlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 10, 20)); xmlPanel.add(button); xmlPanel.add(showXmlBT); xmlPanel.add(saveBT); int y = 0; topPanel.add(new JLabel("Current Tank XML: "), getConstraints(0, y, GridBagConstraints.NONE)); topPanel.add(currentFileLabel, getConstraints(1, y++, GridBagConstraints.HORIZONTAL)); topPanel.add(new JLabel("Select Script Language: "), getConstraints(0, y, GridBagConstraints.NONE)); topPanel.add(languageSelector, getConstraints(1, y++, GridBagConstraints.HORIZONTAL)); topPanel.add(new JLabel("Select Tank XML: "), getConstraints(0, y, GridBagConstraints.NONE)); topPanel.add(xmlPanel, getConstraints(1, y++, GridBagConstraints.HORIZONTAL)); return topPanel; }