List of usage examples for javax.swing JFileChooser getSelectedFile
public File getSelectedFile()
From source file:Main.java
/** * Creates a new JFileChooser and returns the selected path's location. * @param title// ww w. ja va2 s. c o m * @param openTo * @param chooseDirectory * @param filter * @return */ public static String getFilePath(String title, String openTo, boolean chooseDirectory, FileFilter filter) { String location = null; JFileChooser chooser = new JFileChooser(title); chooser.setCurrentDirectory(new File(openTo)); chooser.setFileFilter(filter); chooser.setDialogTitle("Open Cache"); if (chooseDirectory) { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } else { chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); } chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(chooser) == JFileChooser.APPROVE_OPTION) { location = chooser.getSelectedFile().getAbsolutePath(); } return location; }
From source file:kindleclippings.quizlet.QuizletSync.java
private static Map<String, List<Clipping>> readClippingsFile() throws IOException { // try to find it File cl = new File("/Volumes/Kindle/documents/My Clippings.txt"); if (!cl.canRead()) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("Kindle Clippings", "txt")); int result = fc.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) { return null; }// w ww . j av a 2 s . co m cl = fc.getSelectedFile(); } Reader f = new InputStreamReader(new FileInputStream(cl), "UTF-8"); try { MyClippingsReader r = new MyClippingsReader(f); Map<String, List<Clipping>> books = new TreeMap<String, List<Clipping>>(); Clipping l; while ((l = r.readClipping()) != null) { if (l.getType() != ClippingType.highlight && l.getType() != ClippingType.note) { System.err.println("ignored " + l.getType() + " [" + l.getBook() + "]"); continue; } String lct = l.getContent().trim(); if (lct.length() == 0) { System.err.println("ignored empty " + l.getType() + " [" + l.getBook() + "]"); continue; } if (lct.length() < 10 || !lct.contains(" ")) { System.err.println( "ignored too short " + l.getType() + " " + l.getContent() + " [" + l.getBook() + "]"); continue; } List<Clipping> clippings = books.get(l.getBook()); if (clippings == null) { clippings = new ArrayList<Clipping>(); books.put(l.getBook(), clippings); } clippings.add(l); } return books; } finally { f.close(); } }
From source file:com.stam.batchmove.BatchMoveUtils.java
public static void showFilesFrame(Object[][] data, String[] columnNames, final JFrame callerFrame) { final FilesFrame filesFrame = new FilesFrame(); DefaultTableModel model = new DefaultTableModel(data, columnNames) { private static final long serialVersionUID = 1L; @Override/*from w w w .j a v a 2 s .c om*/ public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return column == 0; } }; DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(JLabel.CENTER); final JTable table = new JTable(model); for (int i = 1; i < table.getColumnCount(); i++) { table.setDefaultRenderer(table.getColumnClass(i), renderer); } // table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setRowHeight(30); table.getTableHeader().setFont(new Font("Serif", Font.BOLD, 14)); table.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); table.setRowSelectionAllowed(false); table.getColumnModel().getColumn(0).setMaxWidth(35); table.getColumnModel().getColumn(1).setPreferredWidth(350); table.getColumnModel().getColumn(2).setPreferredWidth(90); table.getColumnModel().getColumn(2).setMaxWidth(140); table.getColumnModel().getColumn(3).setMaxWidth(90); JPanel tblPanel = new JPanel(); JPanel btnPanel = new JPanel(); tblPanel.setLayout(new BorderLayout()); if (table.getRowCount() > 15) { JScrollPane scrollPane = new JScrollPane(table); tblPanel.add(scrollPane, BorderLayout.CENTER); } else { tblPanel.add(table.getTableHeader(), BorderLayout.NORTH); tblPanel.add(table, BorderLayout.CENTER); } btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); filesFrame.setMinimumSize(new Dimension(800, 600)); filesFrame.setLayout(new BorderLayout()); filesFrame.add(tblPanel, BorderLayout.NORTH); filesFrame.add(btnPanel, BorderLayout.SOUTH); final JLabel resultsLabel = new JLabel(); JButton cancelBtn = new JButton("Cancel"); cancelBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filesFrame.setVisible(false); callerFrame.setVisible(true); } }); JButton moveBtn = new JButton("Copy"); moveBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Choose target directory"); int selVal = fileChooser.showOpenDialog(null); if (selVal == JFileChooser.APPROVE_OPTION) { File selection = fileChooser.getSelectedFile(); String targetPath = selection.getAbsolutePath(); DefaultTableModel dtm = (DefaultTableModel) table.getModel(); int nRow = dtm.getRowCount(); int copied = 0; for (int i = 0; i < nRow; i++) { Boolean selected = (Boolean) dtm.getValueAt(i, 0); String filePath = dtm.getValueAt(i, 1).toString(); if (selected) { try { FileUtils.copyFileToDirectory(new File(filePath), new File(targetPath)); dtm.setValueAt("Copied", i, 3); copied++; } catch (Exception ex) { Logger.getLogger(SelectionFrame.class.getName()).log(Level.SEVERE, null, ex); dtm.setValueAt("Failed", i, 3); } } } resultsLabel.setText(copied + " files copied. Finished!"); } } }); btnPanel.add(cancelBtn); btnPanel.add(moveBtn); btnPanel.add(resultsLabel); filesFrame.revalidate(); filesFrame.setVisible(true); callerFrame.setVisible(false); }
From source file:net.sf.jabref.exporter.ExportFormats.java
/** * Create an AbstractAction for performing an export operation. * * @param frame/* www . ja v a2s.c o m*/ * The JabRefFrame of this JabRef instance. * @param selectedOnly * true indicates that only selected entries should be exported, * false indicates that all entries should be exported. * @return The action. */ public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) { class ExportAction extends MnemonicAwareAction { private final JabRefFrame frame; private final boolean selectedOnly; public ExportAction(JabRefFrame frame, boolean selectedOnly) { this.frame = frame; this.selectedOnly = selectedOnly; putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries") : Localization.menuTitle("Export")); } @Override public void actionPerformed(ActionEvent e) { ExportFormats.initAllExports(); JFileChooser fc = ExportFormats .createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY)); fc.showSaveDialog(frame); File file = fc.getSelectedFile(); if (file == null) { return; } FileFilter ff = fc.getFileFilter(); if (ff instanceof ExportFileFilter) { ExportFileFilter eff = (ExportFileFilter) ff; String path = file.getPath(); if (!path.endsWith(eff.getExtension())) { path = path + eff.getExtension(); } file = new File(path); if (file.exists()) { // Warn that the file exists: if (JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", file.getName()), Localization.lang("Export"), JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) { return; } } final IExportFormat format = eff.getExportFormat(); List<BibEntry> entries; if (selectedOnly) { // Selected entries entries = frame.getCurrentBasePanel().getSelectedEntries(); } else { // All entries entries = frame.getCurrentBasePanel().getDatabase().getEntries(); } // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext() .getFileDirectory(); // Make sure we remember which filter was used, to set // the default for next time: Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName()); Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent()); final File finFile = file; final List<BibEntry> finEntries = entries; AbstractWorker exportWorker = new AbstractWorker() { String errorMessage; @Override public void run() { try { format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(), finFile.getPath(), frame.getCurrentBasePanel().getEncoding(), finEntries); } catch (Exception ex) { LOGGER.warn("Problem exporting", ex); if (ex.getMessage() == null) { errorMessage = ex.toString(); } else { errorMessage = ex.getMessage(); } } } @Override public void update() { // No error message. Report success: if (errorMessage == null) { frame.output(Localization.lang("%0 export successful", format.getDisplayName())); } // ... or show an error dialog: else { frame.output(Localization.lang("Could not save file.") + " - " + errorMessage); // Need to warn the user that saving failed! JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + errorMessage, Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE); } } }; // Run the export action in a background thread: exportWorker.getWorker().run(); // Run the update method: exportWorker.update(); } } } return new ExportAction(frame, selectedOnly); }
From source file:de.dakror.virtualhub.server.dialog.BackupEditDialog.java
public static void show() throws JSONException { final JDialog dialog = new JDialog(Server.currentServer.frame, "Backup-Einstellungen", true); dialog.setSize(400, 250);// ww w . j a va 2s . c om dialog.setLocationRelativeTo(Server.currentServer.frame); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); JPanel cp = new JPanel(new SpringLayout()); cp.add(new JLabel("Zielverzeichnis:")); JPanel panel = new JPanel(); final JTextField path = new JTextField((Server.currentServer.settings.has("backup.path") ? Server.currentServer.settings.getString("backup.path") : ""), 10); panel.add(path); panel.add(new JButton(new AbstractAction("Whlen...") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser((path.getText().length() > 0 ? new File(path.getText()) : new File(System.getProperty("user.home")))); jfc.setFileHidingEnabled(false); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.setDialogTitle("Backup-Zielverzeichnis whlen"); if (jfc.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) path.setText(jfc.getSelectedFile().getPath().replace("\\", "/")); } })); cp.add(panel); cp.add(new JLabel("")); cp.add(new JLabel("")); cp.add(new JButton(new AbstractAction("Abbrechen") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } })); cp.add(new JButton(new AbstractAction("Speichern") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { try { if (path.getText().length() > 0) Server.currentServer.settings.put("backup.path", path.getText()); dialog.dispose(); } catch (JSONException e1) { e1.printStackTrace(); } } })); SpringUtilities.makeCompactGrid(cp, 3, 2, 6, 6, 6, 6); dialog.setContentPane(cp); dialog.pack(); dialog.setVisible(true); }
From source file:Main.java
public static String showOpenFile(String currentDirectoryPath, Component parent, final String filterRegex, final String filterDescription) { JFileChooser fileChooser = new JFileChooser(currentDirectoryPath); fileChooser.addChoosableFileFilter(new FileFilter() { private Pattern regexPattern = Pattern.compile(filterRegex); public boolean accept(File f) { if (f.isDirectory()) return true; return regexPattern.matcher(f.getName()).matches(); }/*from w w w . ja va 2 s. c om*/ public String getDescription() { return filterDescription; } }); fileChooser.showOpenDialog(parent); File choosedFile = fileChooser.getSelectedFile(); if (choosedFile == null) return null; return choosedFile.getAbsolutePath(); }
From source file:Main.java
/** * Consistent way to chosing a file to open with JFileChooser. * <p>/*ww w. ja va 2s . com*/ * * @see JFileChooser#setFileSelectionMode(int) * @see #getSystemFiles(Component, int) * @param owner to show the component relative to. * @param mode selection mode for the JFileChooser. * @return File based on the user selection can be null. */ public static File getSystemFile(Component owner, int mode, FileFilter[] filters) { JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(mode); jfc.setFileHidingEnabled(true); jfc.setAcceptAllFileFilterUsed(true); if (filters != null) { for (int i = 0; i < filters.length; i++) { jfc.addChoosableFileFilter(filters[i]); } if (filters.length >= 1) { jfc.setFileFilter(filters[0]); } } int result = jfc.showOpenDialog(owner); if (result == JFileChooser.APPROVE_OPTION) { return jfc.getSelectedFile(); } return null; }
From source file:grafix.principal.Comandos.java
static public void cmdSalvarConfiguracao() { ControleRegistro.alertaRegistro();// w w w. j a va 2 s . com JFileChooser chooser = new JFileChooser(new File(ConfiguracoesGrafix.PASTA_TEMPLATES)); chooser.setSelectedFile(new File(ConfiguracoesGrafix.EXTENSAO_TEMPLATES)); chooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = chooser.showSaveDialog(Controle.getTela()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { Controle.getConfiguracoesUsuario().setNome(file.getName()); Controle.salvarConfiguracoesUsuario(true); LeitorArquivoConfiguracao.getInstance().criarCopia(file); } catch (Exception ex) { ex.printStackTrace(); } } Controle.getTela().getComboConfiguracoes().popularCombo(); }
From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java
private static JFileChooser initFileChooser(JFileChooser fileChooser, FileFilter filter) { if (fileChooser.getSelectedFile() != null) { // reusing the dialog fileChooser = new JFileChooser(fileChooser.getSelectedFile().getPath()); }// w w w . j a va 2 s. c o m if (filter != null) { fileChooser.setFileFilter(filter); } return fileChooser; }
From source file:Main.java
/** * Dialog for choosing file.//from w w w . ja v a 2s.c om * * @param parent the parent component of the dialog, can be null * @return selected file or null if no file is selected */ public static File chooseImageFile(Component parent) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileFilter() { @Override public String getDescription() { return "Supported image files(JPEG, PNG, BMP)"; } @Override public boolean accept(File f) { String name = f.getName(); boolean accepted = f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".bmp"); return accepted; } }); fileChooser.showOpenDialog(parent); return fileChooser.getSelectedFile(); }