protected void selectFile() { ResourceManager rm = ResourceManager.all(FilePropertyEditor.class); JFileChooser chooser = UserPreferences.getDefaultDirectoryChooser(); chooser.setDialogTitle(rm.getString("DirectoryPropertyEditor.dialogTitle")); chooser.setApproveButtonText(rm.getString("DirectoryPropertyEditor.approveButtonText")); chooser.setApproveButtonMnemonic(rm.getChar("DirectoryPropertyEditor.approveButtonMnemonic")); File oldFile = (File) getValue(); if (oldFile != null && oldFile.isDirectory()) { try { chooser.setCurrentDirectory(oldFile.getCanonicalFile()); } catch (IOException e) { e.printStackTrace(); } } if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(editor)) { File newFile = chooser.getSelectedFile(); String text = newFile.getAbsolutePath(); textfield.setText(text); firePropertyChange(oldFile, newFile); } }
public boolean exportToTxtFile() { Internal internal = BookUtil.get( this.mainFrame, SbConstants.BookKey.EXPORT_DIRECTORY, EnvUtil.getDefaultExportDir(this.mainFrame)); File file1 = new File(internal.getStringValue()); JFileChooser chooser = new JFileChooser(file1); chooser.setApproveButtonText(I18N.getMsg("msg.common.export")); chooser.setSelectedFile(new File(getFileName())); chooser.setFileFilter(new TextFileFilter()); int i = chooser.showOpenDialog(this.mainFrame); if (i == 1) { return false; } File outFile = chooser.getSelectedFile(); if (!outFile.getName().endsWith(".txt")) { outFile = new File(outFile.getPath() + ".txt"); } StringBuffer buffer = getContent(); try { try (BufferedWriter outStream = new BufferedWriter(new FileWriter(outFile))) { String str = buffer.toString(); outStream.write(HtmlUtil.htmlToText(str, true)); } } catch (IOException e) { return false; } JOptionPane.showMessageDialog( this.mainFrame, I18N.getMsg("msg.common.export.success") + "\n" + outFile.getAbsolutePath(), I18N.getMsg("msg.common.export"), 1); return true; }
private void setupFileChooser() { fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Select directory to output ISArchive to..."); fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); fileChooser.setApproveButtonText("Output to selected directory"); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); }
private void importProjectAndData() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setApproveButtonText("Importa"); fileChooser.setDialogTitle("Importa progetto e dati"); fileChooser.addChoosableFileFilter(new GenericFileFilter(".atd", "Arduino Trend Data")); int n = fileChooser.showOpenDialog(view); if (n == JFileChooser.APPROVE_OPTION) { try { project.importProjectAndData(fileChooser.getSelectedFile()); file = null; inizializePens(project.getPenModels()); modelListPens.update(null, null); view.setTitle(project.getTitle()); view.trend.setModel(project.getTrendModel()); view.trend.setMillsAtFirstRecord(); } catch (IOException e) { view.popupErrorMessage(e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { view.popupErrorMessage("File non trovato"); e.printStackTrace(); } } }
private void outputFolderBtnActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_outputFolderBtnActionPerformed if (chooser == null) { chooser = new JFileChooser(); chooser.setApproveButtonText(options.getMsg("export_project_selectFolder")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } outputFolder = StrUtils.nullableString(outputFolderText.getText()); if (outputFolder != null) { try { File f = new File(outputFolder); if (!f.exists()) { f.mkdirs(); } chooser.setSelectedFile(f); } catch (Exception ex) { // Unable to create folders. By now, do nothing } } if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { outputFolder = chooser.getSelectedFile().getAbsolutePath(); outputFolderText.setText(outputFolder); } } // GEN-LAST:event_outputFolderBtnActionPerformed
private JFileChooser initFileChooser(String choice) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); fileChooser.setFileFilter(new FileNameExtensionFilter("Ser Files", "ser")); fileChooser.setApproveButtonText(choice); fileChooser.setDialogTitle(choice); return fileChooser; }
/** * Displays a custom file chooser sheet with a custom approve button. * * @param chooser the chooser * @param parent the parent component of the dialog; can be {@code null} * @param approveButtonText the text of the {@code ApproveButton} * @param listener The listener for SheetEvents. */ public static void showSheet( final JFileChooser chooser, Component parent, String approveButtonText, SheetListener listener) { if (approveButtonText != null) { chooser.setApproveButtonText(approveButtonText); chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); } // Begin Create Dialog Frame frame = parent instanceof Frame ? (Frame) parent : (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); String title = chooser.getUI().getDialogTitle(chooser); chooser.getAccessibleContext().setAccessibleDescription(title); final JSheet sheet = new JSheet(frame); sheet.addSheetListener(listener); Container contentPane = sheet.getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(chooser, BorderLayout.CENTER); // End Create Dialog final ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent evt) { int option; if (evt.getActionCommand().equals("ApproveSelection")) { option = JFileChooser.APPROVE_OPTION; } else { option = JFileChooser.CANCEL_OPTION; } sheet.hide(); sheet.fireOptionSelected(chooser, option); chooser.removeActionListener(this); } }; chooser.addActionListener(actionListener); sheet.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { sheet.fireOptionSelected(chooser, JFileChooser.CANCEL_OPTION); chooser.removeActionListener(actionListener); } }); chooser.rescanCurrentDirectory(); sheet.pack(); sheet.show(); sheet.toFront(); }
/** * Returns a new <tt>JFileChooser</tt> instance for selecting directories and with * internationalized strings for the caption and the selection button. * * @param approveKey can be <code>null</code> * @param directory can be <code>null</code> * @param filter can be <code>null</code> * @return a new <tt>JFileChooser</tt> instance for selecting directories. */ private static JFileChooser getDirectoryChooser( String titleKey, String approveKey, File directory, int mode, FileFilter filter) { JFileChooser chooser = null; if (directory == null) directory = getLastInputDirectory(); if (directory == null) { chooser = new JFileChooser(); } else { try { chooser = new JFileChooser(directory); } catch (NullPointerException e) { // Workaround for JRE bug 4711700. A NullPointer is thrown // sometimes on the first construction under XP look and feel, // but construction succeeds on successive attempts. try { chooser = new JFileChooser(directory); } catch (NullPointerException npe) { // ok, now we use the metal file chooser, takes a long time to load // but the user can still use the program UIManager.getDefaults().put("FileChooserUI", "javax.swing.plaf.metal.MetalFileChooserUI"); chooser = new JFileChooser(directory); } } catch (ArrayIndexOutOfBoundsException ie) { // workaround for Windows XP, not sure if second try succeeds // then chooser = new JFileChooser(directory); } } if (filter != null) { chooser.setFileFilter(filter); } else { if (mode == JFileChooser.DIRECTORIES_ONLY) { chooser.setFileFilter( new FileFilter() { public boolean accept(File file) { return true; } public String getDescription() { return I18n.tr("All Folders"); } }); } } chooser.setFileSelectionMode(mode); String title = I18n.tr(titleKey); chooser.setDialogTitle(title); if (approveKey != null) { String approveButtonText = I18n.tr(approveKey); chooser.setApproveButtonText(approveButtonText); } return chooser; }
public void selectFile() { final JFileChooser chooser = new JFileChooser(overlays.defaultDirectory); chooser.setFileFilter( GuiUtils.getCustomFileFilter(I18n.text("LSF log files"), new String[] {"lsf", "lsf.gz"})); chooser.setApproveButtonText(I18n.text("Open Log")); int option = chooser.showOpenDialog(overlays.getConsole()); if (option != JFileChooser.APPROVE_OPTION) return; else { Thread logLoading = new Thread( new Runnable() { @Override public void run() { final ProgressMonitor monitor = new ProgressMonitor( overlays.getConsole(), I18n.text("Opening LSF log"), I18n.text("Opening LSF log"), 0, 100); try { clearOverlays(); fileLabel.setText("loading..."); logFile = chooser.getSelectedFile(); LsfLogSource source = new LsfLogSource( chooser.getSelectedFile(), new LsfIndexListener() { @Override public void updateStatus(String messageToDisplay) { monitor.setNote(messageToDisplay); } }); logSource = source; loadOverlays(source); } catch (Exception e) { GuiUtils.errorMessage(overlays.getConsole(), e); } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { fileLabel.setText(chooser.getSelectedFile().getParentFile().getName()); } }); monitor.close(); overlays.defaultDirectory = chooser.getSelectedFile().getParent(); } }); logLoading.start(); } }
private String getFileName(String title, String okButton, String currentDirectory) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(title); fileChooser.setApproveButtonText(okButton); fileChooser.setCurrentDirectory(new File(currentDirectory)); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); return selectedFile.getAbsolutePath(); } return null; }
@Action public void browse() { File l = new File(diskLocation); if (l.isDirectory()) { chooser.setCurrentDirectory(l); } chooser.setApproveButtonText("Select"); int returnval = chooser.showOpenDialog(null); if (returnval == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); setDiskLocation(f.getAbsolutePath()); } } // GEN-LAST:event_selectType
/** Creates new form ConfigDialog */ public ConfigDialog() { initComponents(); saveNames = Arrays.asList( saveNameTextField1, saveNameTextField2, saveNameTextField3, saveNameTextField4); savePaths = Arrays.asList( savePathTextField1, savePathTextField2, savePathTextField3, savePathTextField4); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setApproveButtonText(messages.getString("select")); }
private void createSaveButton() { saveButton = new JButton("Save"); fileChooser = new JFileChooser(); fileChooser.setApproveButtonText("Export"); fileChooser.setApproveButtonToolTipText("Export your file!"); saveButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int retrival = fileChooser.showOpenDialog(null); if (retrival == JFileChooser.APPROVE_OPTION) { // IF A FILE WAS // CHOSEN THE IF // STATEMENT IS // TRUE try (PrintStream fw = new PrintStream(fileChooser.getSelectedFile() + ".txt")) { fw.println("To: " + toField.getText()); fw.println( "____________________________________________________________________________________________________________"); fw.println(); fw.println("Subject: " + subjectField.getText()); fw.println( "____________________________________________________________________________________________________________"); fw.println(); char[] textAreaArray = referenceTextArea.getText().toCharArray(); StringBuilder textAreaStringBuilder = new StringBuilder(); for (int i = 0; i < textAreaArray.length; i++) { textAreaStringBuilder.append(textAreaArray[i]); if (i == 30) { fw.println(); } } fw.println(textAreaStringBuilder.toString()); } catch (Exception ex) { ex.printStackTrace(); } } } }); }
/** * Creates a new BrowseButtonAction and initializes it with filters. * * @param filters filter collection * @param allFilters wheter the all files filter should be included */ public BrowseButtonAction(HashMap<String, String[]> filters, boolean allFilters) { super(); fileChooser = new JFileChooser(); fileChooser.setApproveButtonText(_("Ok")); fileChooser.setAcceptAllFileFilterUsed(allFilters); for (String description : filters.keySet()) { FileNameExtensionFilter filter = new FileNameExtensionFilter(description, filters.get(description)); fileChooser.addChoosableFileFilter(filter); } this.filters = filters; }
private void openRecordPathFileChooser() { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setApproveButtonText(ControlMain.getProperty("msg_choose")); fc.setApproveButtonToolTipText(ControlMain.getProperty("msg_chooseDirectory")); int returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { String path = fc.getSelectedFile().toString(); this.getView().getJTextFieldRecordSavePath().setText(path); this.getTimer().setSavePath(path); } }
private void selectFolder() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(textFolder.getText())); fileChooser.setDialogTitle(CAPTION_SELECT_FOLDER); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setApproveButtonText("Select"); fileChooser.setApproveButtonToolTipText(TOOL_TIP_SELECT_FOLDER); if (fileChooser.showOpenDialog(FileTransferServer.this) == JFileChooser.APPROVE_OPTION) { // Get the selected file String path = fileChooser.getSelectedFile().getPath() + "\\"; textFolder.setText(path); } }
public void init() { tabbedPane.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.getModifiers() == InputEvent.BUTTON3_MASK) { contextMenu.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseReleased(MouseEvent e) {} }); fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Save file"); fileChooser.setApproveButtonText("Save file"); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); }
/** Action to perform */ public void actionPerformed(ActionEvent e) { if (e.getSource() == appdirChooser) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Select an Application Directory"); fileChooser.setApproveButtonText("OK"); if (!appDirTF.getText().equals("")) fileChooser.setCurrentDirectory(new File(appDirTF.getText())); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(this); // if we selected an image, load the image if (result == JFileChooser.APPROVE_OPTION) { String path = fileChooser.getSelectedFile().getPath(); appDirTF.setText(path); } } }
private void localizarButtonActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_localizarButtonActionPerformed try { JFileChooser chooser = null; if (StringHelper.isBlank(field.getText())) { chooser = new JFileChooser(System.getProperty("user.home")); } else { chooser = new JFileChooser(field.getText()); } FileNameExtensionFilter extension = new FileNameExtensionFilter("Arquivo Xml (*.xml)", "xml"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileFilter(extension); chooser.setFileHidingEnabled(true); chooser.setMultiSelectionEnabled(true); chooser.setApproveButtonText("Abrir"); int choice = chooser.showOpenDialog(this); if (choice == JFileChooser.APPROVE_OPTION) { File oneFile = chooser.getSelectedFile(); String path = null; path = oneFile.getPath(); String nomeArquivo = StringHelper.substringAfterLast(path, SO.getSepArqSO()); String caminhoArq = StringHelper.substringBeforeLast(path, SO.getSepArqSO()); if (defaultListModel.contains(new InfoArq(nomeArquivo, caminhoArq))) { throw new Exception("O arquivo com este mesmo caminho ja existe na lista abaixo!"); } field.setText(path.substring(0, path.lastIndexOf(SO.getSepArqSO()))); File[] files = chooser.getSelectedFiles(); for (File file : files) { defaultListModel.addElement( new InfoArq( file.getName(), StringHelper.substringBeforeLast(file.getPath(), SO.getSepArqSO()))); } } } catch (Exception ex) { ex.printStackTrace(); JMessageUtil.showInfoMessage(this, ex.getMessage()); } } // GEN-LAST:event_localizarButtonActionPerformed
// When called, opens a file chooser public static void start() { FileNameExtensionFilter filter = new FileNameExtensionFilter("Synth File", ".synth"); JFileChooser saveFile = new JFileChooser(); // Set file chooser properties saveFile.setDialogTitle("Save"); saveFile.setApproveButtonText("Save"); saveFile.setSelectedFile(new File(filename)); saveFile.setFileFilter(filter); // If valid choice is made, run fileWrite with this file if (saveFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { filename = saveFile.getSelectedFile().getName(); fileWrite(saveFile.getCurrentDirectory().toString()); } }
/** Constructor */ public SaverCustomizer() { try { m_SaverEditor.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { repaint(); if (m_dsSaver != null) { System.err.println("Property change!!"); m_dsSaver.setSaver(m_dsSaver.getSaver()); } } }); repaint(); } catch (Exception ex) { ex.printStackTrace(); } setLayout(new BorderLayout()); m_fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); m_fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); m_fileChooser.setApproveButtonText("Select directory"); m_fileChooser.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { try { File selectedFile = m_fileChooser.getSelectedFile(); m_directoryText.setText(selectedFile.toString()); /* (m_dsSaver.getSaver()).setFilePrefix(m_prefixText.getText()); (m_dsSaver.getSaver()).setDir(m_fileChooser.getSelectedFile().getPath()); m_dsSaver. setRelationNameForFilename(m_relationNameForFilename.isSelected()); */ } catch (Exception ex) { ex.printStackTrace(); } } // closing if (m_fileChooserFrame != null) { m_fileChooserFrame.dispose(); } } }); }
private void exportProjectAndData() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setApproveButtonText("Esporta"); fileChooser.setDialogTitle("Esporta progetto e dati"); fileChooser.addChoosableFileFilter(new GenericFileFilter(".csv", "File generico csv")); fileChooser.addChoosableFileFilter(new GenericFileFilter(".atd", "Arduino Trend Data")); int n = fileChooser.showSaveDialog(view); if (n == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); FileFilter currentFilter = fileChooser.getFileFilter(); if (currentFilter instanceof GenericFileFilter) { String ext = ((GenericFileFilter) currentFilter).getExtension(); if (file.getName().endsWith(ext) == false) { try { file = new File(file.getCanonicalPath() + ext); } catch (IOException e) { e.printStackTrace(); } } } int a = JOptionPane.OK_OPTION; if (file.exists()) { a = JOptionPane.showConfirmDialog(view, "Vuoi sovrascire il file?"); } switch (a) { case JOptionPane.OK_OPTION: try { project.exportProject(file, pens, view.trend.getModel()); } catch (IOException e) { view.popupErrorMessage(e.getMessage()); e.printStackTrace(); } break; case JOptionPane.NO_OPTION: exportProjectAndData(); break; case JOptionPane.CANCEL_OPTION: System.out.println("CANCEL"); break; } } }
/** Uses a {@link JFileChooser} to get a database location */ private static String chooseDatabaseLocation(final IWindowUtils windowUtils) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Select Database"); fileChooser.setApproveButtonText("Use this Database"); final int result = fileChooser.showDialog(null, null); if (result == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile().getAbsolutePath(); } else { if (windowUtils.showWarningQuestionMessage( "Apprentice needs a database!\nDo you want to go back and select or create a new one?\nOtherwise the program will terminate.", "Database")) { return chooseDatabaseLocation(windowUtils); } else { LOG.info("Shut down due to lack of database."); System.exit(0); } } return ""; // kinda unreachable }
/** 实现对打开文件的处理 */ public void openAnswer() { if (answer == 0) { cb.canPlay = true; File file = null; JFileChooser fileChooser = new JFileChooser(); fileChooser.setApproveButtonText("确定"); fileChooser.setDialogTitle("打开文件"); fileChooser.setCurrentDirectory(new File("SavaAndOpen")); int result = fileChooser.showOpenDialog(gc); // 显示选择框 if (result == JFileChooser.APPROVE_OPTION) { // 选择的是确定按钮 file = fileChooser.getSelectedFile(); // 得到选择的文件 cb.repaint(); } if (file != null) { try { DataInputStream dis = new DataInputStream(new FileInputStream(file)); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { allChess[i][j] = dis.readInt(); } } cb.message = dis.readUTF(); cb.isBlack = dis.readBoolean(); if (cb.isBlack == false) { // 如果是和电脑下且轮到白子下 cb.ch.playWithCom(); } cb.changeColor = dis.readBoolean(); cb.isStop = dis.readBoolean(); if (cb.computerPlay == false) { // 如果不和电脑下,发送信息 cb.send(cc.dos); } dis.close(); cb.repaint(); } catch (Exception e1) { } } } if (answer != 0) { JOptionPane.showMessageDialog(cb, "对方拒绝了你的请求!"); } answer = 3; }
/** * Load the app configuration from the external file * * @param path The full path of the configuration file */ private void loadFromFile() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Select a Model File"); fileChooser.setApproveButtonText("OK"); if (!pictureFileName.getText().equals("")) fileChooser.setCurrentDirectory(new File(pictureFileName.getText())); else { try { if (engine.appManager.currentApp.getAppDir() != null) fileChooser.setCurrentDirectory(new File(engine.appManager.currentApp.getAppDir())); } catch (Exception ex) { } } fileChooser.setFileFilter( new FileFilterUtils(new String[] {"xml"}, true, "XML File (*.xml)")); int result = fileChooser.showOpenDialog(this); // if we selected an image, load the image if (result == JFileChooser.APPROVE_OPTION) { String path = fileChooser.getSelectedFile().getPath(); pictureFileName.setText(path.trim()); } }
public void setPath() { if (saveDir == null) { saveDir = DirectoryManager.getUserHomeDirectory(); } JFileChooser fc = new JFileChooser(saveDir); fc.setApproveButtonText("Set"); // fc.setDialogType(JFileChooser.SAVE_DIALOG ); fc.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); fc.setMultiSelectionEnabled(false); int returnVal = fc.showOpenDialog(null); // int returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { saveDir = fc.getSelectedFile(); getSaveDirTextField().setText(saveDir.getPath()); } // String srcDirName = getWorkDirComboBox().getSelectedItem().toString(); // File dst = new File (saveDir, srcDirName); }
public void actionPerformed(ActionEvent ae) { JDialog saveDialog = new JDialog(MainFrame.getInstance(), "Save Termbank as CSV", true); MainFrame.getGuiRoots().add(saveDialog); saveDialog.setLayout(new BorderLayout()); SliderPanel sliderPanel = new SliderPanel(termbank, "save", true, null); saveDialog.add(sliderPanel, BorderLayout.CENTER); JPanel chooserPanel = new JPanel(); chooserPanel.setLayout(new BoxLayout(chooserPanel, BoxLayout.Y_AXIS)); chooserPanel.add(new JSeparator()); JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV files", Utilities.EXTENSION_CSV); chooser.setFileFilter(filter); chooser.setApproveButtonText("Save"); chooser.addActionListener( new CsvFileSelectionActionListener(chooser, termbank, sliderPanel, saveDialog, Mode.SAVE)); chooserPanel.add(chooser); saveDialog.add(chooserPanel, BorderLayout.SOUTH); saveDialog.pack(); saveDialog.setLocationRelativeTo(saveDialog.getOwner()); saveDialog.setVisible(true); }
/** Allows subclasses to modify the chooser to suit their needs. */ protected JFileChooser createFileChooser() { File originalFile = (File) getValue(); final JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(mode); if (originalFile != null && originalFile.getParent() != null) chooser.setCurrentDirectory(new File(originalFile.getParent())); chooser.setSelectedFile(originalFile); chooser.setApproveButtonText(bundle.getString("CTL_ApproveSelect")); chooser.setApproveButtonToolTipText(bundle.getString("CTL_ApproveSelectToolTip")); switch (mode) { case JFileChooser.FILES_AND_DIRECTORIES: chooser.setDialogTitle(bundle.getString("CTL_DialogTitleFilesAndDirs")); break; case JFileChooser.FILES_ONLY: chooser.setDialogTitle(bundle.getString("CTL_DialogTitleFiles")); break; case JFileChooser.DIRECTORIES_ONLY: chooser.setDialogTitle(bundle.getString("CTL_DialogTitleDirs")); break; } return chooser; }
@Override public void actionPerformed(final ActionEvent e) { beforeAction(e); final ResourceBundle appMessages = ResourceBundle.getBundle( "application", ServiceLocator.get(ConfigurationManager.class).get().getLocale()); final Component parent; if (e.getSource() instanceof Component) parent = (Component) e.getSource(); else parent = null; JFileChooser chooser = new JFileChooser(); File defaultFile = ServiceLocator.get(ConfigurationManager.class).get().getLastExportPath().getParentFile(); chooser.setCurrentDirectory(defaultFile); chooser.setFileFilter( new FileNameExtensionFilter("*." + format.toString().toLowerCase(), format.toString())); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setApproveButtonText(appMessages.getString("exportDialog.approve")); chooser.setApproveButtonMnemonic( KeyStroke.getKeyStroke(appMessages.getString("exportDialog.approve.mnemonic")) .getKeyCode()); chooser.setApproveButtonToolTipText( ServiceLocator.get(TooltipFactory.class) .getDecorated( appMessages.getString("exportDialog.approve.tooltip.message"), appMessages.getString("exportDialog.approve.tooltip.title"), "save.png", KeyStroke.getKeyStroke( "alt " + appMessages.getString("exportDialog.approve.mnemonic")))); if (chooser.showDialog(parent, null) == JFileChooser.APPROVE_OPTION) { chooserApproved(e); File f = chooser.getSelectedFile(); if (!chooser.accept(f)) { f = new File(f.toString() + "." + format.toString().toLowerCase()); } ServiceLocator.get(ConfigurationManager.class).get().setLastExportPath(f); if (f.exists()) { if (JOptionPane.showConfirmDialog( parent, MessageFormat.format( appMessages.getString("exportDialog.overwrite"), new Object[] {f}), appMessages.getString("exportDialog.overwrite.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null) != JOptionPane.YES_OPTION) { return; } } final File file = f; final ExportOptions options = format.askForOptions(origami); final JDialog progressDialog = new JDialog(); final JProgressBar bar = new JProgressBar(0, format.getNumOfProgressChunks(origami, options)); bar.setStringPainted(true); bar.setString(appMessages.getString("exporting.no.percentage")); progressDialog.getContentPane().setLayout(new FlowLayout()); progressDialog.setUndecorated(true); progressDialog.setAlwaysOnTop(true); progressDialog.setLocationRelativeTo(null); final SwingWorker<Set<File>, Void> worker = new SwingWorker<Set<File>, Void>() { private int chunksReceived = 0; @Override protected Set<File> doInBackground() throws Exception { final Runnable progressCallback = new Runnable() { @Override public void run() { publish(new Void[] {null}); if (isCancelled()) throw new RuntimeException(); } }; return ServiceLocator.get(OrigamiHandler.class) .export(origami, file, format, options, progressCallback); } @Override protected void process(List<Void> chunks) { chunksReceived += chunks.size(); bar.setValue(chunksReceived); bar.setString( MessageFormat.format( appMessages.getString("exporting.percentage"), bar.getPercentComplete())); } @Override protected void done() { progressDialog.setVisible(false); progressDialog.dispose(); try { if (!isCancelled()) { Set<File> resultFiles = get(); StringBuilder b = new StringBuilder(); for (File f : resultFiles) b.append("\n").append(f.toString()); JOptionPane.showMessageDialog( parent, MessageFormat.format( appMessages.getString("exportSuccessful.message"), new Object[] {b.toString(), resultFiles.size()}), appMessages.getString("exportSuccessful.title"), JOptionPane.INFORMATION_MESSAGE, null); } } catch (HeadlessException e) { JOptionPane.showMessageDialog( parent, MessageFormat.format( appMessages.getString("failedToExport.message"), new Object[] {file.toString()}), appMessages.getString("failedToExport.title"), JOptionPane.ERROR_MESSAGE, null); Logger.getLogger("application").warn("Unable to export origami.", e); } catch (InterruptedException e) { JOptionPane.showMessageDialog( parent, MessageFormat.format( appMessages.getString("failedToExport.message"), new Object[] {file.toString()}), appMessages.getString("failedToExport.title"), JOptionPane.ERROR_MESSAGE, null); Logger.getLogger("application").warn("Unable to export origami.", e); } catch (ExecutionException e) { JOptionPane.showMessageDialog( parent, MessageFormat.format( appMessages.getString("failedToExport.message"), new Object[] {file.toString()}), appMessages.getString("failedToExport.title"), JOptionPane.ERROR_MESSAGE, null); Logger.getLogger("application").warn("Unable to export origami.", e); } ExportAction.this.done(e); } }; progressDialog.getContentPane().add(bar); JButton cancel = new JButton(); cancel.setAction( new AbstractAction() { /** */ private static final long serialVersionUID = 104733262578076493L; @Override public void actionPerformed(ActionEvent e) { worker.cancel(true); } }); cancel.setText(appMessages.getString("buttons.cancel")); progressDialog.getContentPane().add(cancel); progressDialog.pack(); progressDialog.setVisible(true); worker.execute(); } else { if (e.getSource() instanceof JComponent) ((JComponent) e.getSource()).setCursor(Cursor.getDefaultCursor()); } }
/** * Creates a new BrowseButtonAction and initializes it. */ public BrowseButtonAction() { super(); fileChooser = new JFileChooser(); fileChooser.setApproveButtonText(_("Ok")); }