Search in sources :

Example 36 with FileNameExtensionFilter

use of javax.swing.filechooser.FileNameExtensionFilter in project JMRI by JMRI.

the class FullBackupImportAction method actionPerformed.

@Override
public void actionPerformed(ActionEvent e) {
    // ensure preferences will be found for read
    FileUtil.createDirectory(LocoFile.getFileLocation());
    // make sure instance loaded
    Roster.getDefault();
    // set up to read import file
    ZipInputStream zipper = null;
    FileInputStream inputfile = null;
    try {
        JFileChooser chooser = new JFileChooser();
        String roster_filename_extension = "roster";
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JMRI full roster files", roster_filename_extension);
        chooser.addChoosableFileFilter(filter);
        int returnVal = chooser.showOpenDialog(mParent);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }
        String filename = chooser.getSelectedFile().getAbsolutePath();
        inputfile = new FileInputStream(filename);
        zipper = new ZipInputStream(inputfile) {

            @Override
            public void close() {
            }
        };
        // now iterate through each item in the stream. The get next
        // entry call will return a ZipEntry for each file in the
        // stream
        ZipEntry entry;
        while ((entry = zipper.getNextEntry()) != null) {
            log.debug(String.format("Entry: %s len %d added %TD", entry.getName(), entry.getSize(), new Date(entry.getTime())));
            // reading until read returns 0 or less.
            try {
                // need a dummy object to do this operation in next line
                LocoFile xfile = new LocoFile();
                Element lroot = xfile.rootFromInputStream(zipper).clone();
                if (lroot.getChild("locomotive") == null) {
                    // that's the roster file
                    continue;
                }
                mToID = lroot.getChild("locomotive").getAttributeValue("id");
                // see if user wants to do it
                int retval = JOptionPane.showOptionDialog(mParent, Bundle.getMessage("ConfirmImportID", mToID), Bundle.getMessage("ConfirmImport"), 0, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { Bundle.getMessage("CancelImports"), Bundle.getMessage("Skip"), Bundle.getMessage("ButtonOK") }, null);
                if (retval == 0) {
                    break;
                }
                if (retval == 1) {
                    continue;
                }
                // see if duplicate
                RosterEntry currentEntry = Roster.getDefault().getEntryForId(mToID);
                if (currentEntry != null) {
                    retval = JOptionPane.showOptionDialog(mParent, Bundle.getMessage("ConfirmImportDup", mToID), Bundle.getMessage("ConfirmImport"), 0, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { Bundle.getMessage("CancelImports"), Bundle.getMessage("Skip"), Bundle.getMessage("ButtonOK") }, null);
                    if (retval == 0) {
                        break;
                    }
                    if (retval == 1) {
                        continue;
                    }
                    // turn file into backup
                    // need a dummy object to do this operation in next line
                    LocoFile df = new LocoFile();
                    df.makeBackupFile(LocoFile.getFileLocation() + currentEntry.getFileName());
                    // delete entry
                    Roster.getDefault().removeEntry(currentEntry);
                }
                loadEntryFromElement(lroot);
                addToEntryToRoster();
                // use the new roster
                Roster.getDefault().reloadRosterFile();
            } catch (org.jdom2.JDOMException ex) {
                ex.printStackTrace();
            }
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputfile != null) {
            try {
                // zipper.close() is meaningless, see above, but this will do
                inputfile.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) Element(org.jdom2.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) FileInputStream(java.io.FileInputStream) Date(java.util.Date) ZipInputStream(java.util.zip.ZipInputStream) JFileChooser(javax.swing.JFileChooser)

Example 37 with FileNameExtensionFilter

use of javax.swing.filechooser.FileNameExtensionFilter in project ChatGameFontificator by GlitchCog.

the class ControlWindow method getTargetSaveFile.

/**
     * Gets a file to save to from the given file chooser, including options to overwrite
     * 
     * @param chooser
     *            the chooser to use to get the file
     * @param extension
     *            the extension of the type of file being saved, or null if there is no default extension
     * @return file or null if selection is canceled
     */
public static File getTargetSaveFile(JFileChooser chooser, String extension) {
    int overwrite = JOptionPane.YES_OPTION;
    // overwrite an existing file, but if they select cancel it just breaks out of the loop
    do {
        int result = chooser.showSaveDialog(me);
        // Default to yes, so it writes even if there's no existing file
        overwrite = JOptionPane.YES_OPTION;
        if (result == JFileChooser.APPROVE_OPTION) {
            File saveFile = chooser.getSelectedFile();
            if (chooser.getFileFilter() instanceof FileNameExtensionFilter) {
                String[] exts = ((FileNameExtensionFilter) (chooser.getFileFilter())).getExtensions();
                boolean endsInExt = false;
                for (String ext : exts) {
                    if (saveFile.getName().toLowerCase().endsWith(ext.toLowerCase())) {
                        endsInExt = true;
                        break;
                    }
                }
                if (extension != null && !endsInExt) {
                    saveFile = new File(saveFile.getPath() + "." + extension);
                }
            }
            if (saveFile.exists()) {
                overwrite = JOptionPane.showConfirmDialog(me, "File " + saveFile.getName() + " already exists. Overwrite?", "Overwrite?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            }
            if (overwrite == JOptionPane.YES_OPTION) {
                return saveFile;
            }
        }
    } while (overwrite == JOptionPane.NO_OPTION);
    return null;
}
Also used : FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) File(java.io.File)

Example 38 with FileNameExtensionFilter

use of javax.swing.filechooser.FileNameExtensionFilter in project pcgen by PCGen.

the class InitiativePlugin method fileOpen.

/**
	 * Handles the clicking of the <b>Add </b> button on the GUI.
	 */
public void fileOpen() {
    JFileChooser chooser = ImagePreview.decorateWithImagePreview(new JFileChooser());
    File defaultFile = new File(PCGenSettings.getPcgDir());
    if (defaultFile.exists()) {
        chooser.setCurrentDirectory(defaultFile);
    }
    // TODO should probably handle zip pcg
    String[] pcgs = { "pcg", "pcp" };
    String[] init = { "gmi", "init" };
    FileFilter ff = new FileNameExtensionFilter("Initiative Export", init);
    chooser.addChoosableFileFilter(ff);
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PCGen File", pcgs));
    chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter());
    chooser.setFileFilter(ff);
    chooser.setMultiSelectionEnabled(true);
    Cursor originalCursor = theView.getCursor();
    theView.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    int option = chooser.showOpenDialog(theView);
    if (option == JFileChooser.APPROVE_OPTION) {
        File[] pcFiles = chooser.getSelectedFiles();
        for (File pcFile : pcFiles) {
            if (PCGFile.isPCGenCharacterOrPartyFile(pcFile)) {
                messageHandler.handleMessage(new RequestOpenPlayerCharacterMessage(this, pcFile, false));
            //loadPCG(pcFiles[i]);
            } else if (pcFile.toString().endsWith(".init") || pcFile.toString().endsWith(".gmi")) {
                loadINIT(pcFile);
            }
        }
        /* loop through selected files */
        theView.refreshTable();
    } else {
    /* this means the file is invalid */
    }
    theView.setCursor(originalCursor);
}
Also used : RequestOpenPlayerCharacterMessage(pcgen.pluginmgr.messages.RequestOpenPlayerCharacterMessage) JFileChooser(javax.swing.JFileChooser) FileFilter(javax.swing.filechooser.FileFilter) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) Cursor(java.awt.Cursor) PCGFile(pcgen.io.PCGFile) File(java.io.File)

Example 39 with FileNameExtensionFilter

use of javax.swing.filechooser.FileNameExtensionFilter in project pcgen by PCGen.

the class PCGTrackerPlugin method handleOpen.

/**
	 * Handles the clicking of the <b>Add</b> button on the GUI.
	 */
public void handleOpen() {
    File defaultFile = new File(PCGenSettings.getPcgDir());
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(defaultFile);
    String[] pcgs = { FILENAME_PCG, FILENAME_PCP };
    FileFilter ff = new FileNameExtensionFilter(LanguageBundle.getString("in_pcgen_file"), //$NON-NLS-1$
    pcgs);
    chooser.addChoosableFileFilter(ff);
    chooser.setFileFilter(ff);
    chooser.setMultiSelectionEnabled(true);
    Component component = GMGenSystem.inst;
    Cursor originalCursor = component.getCursor();
    component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    int option = chooser.showOpenDialog(GMGenSystem.inst);
    if (option == JFileChooser.APPROVE_OPTION) {
        for (File selectedFile : chooser.getSelectedFiles()) {
            if (PCGFile.isPCGenCharacterOrPartyFile(selectedFile)) {
                messageHandler.handleMessage(new RequestOpenPlayerCharacterMessage(this, selectedFile, false));
            }
        }
    } else {
    /* this means the file is invalid */
    }
    GMGenSystem.inst.setCursor(originalCursor);
}
Also used : RequestOpenPlayerCharacterMessage(pcgen.pluginmgr.messages.RequestOpenPlayerCharacterMessage) JFileChooser(javax.swing.JFileChooser) FileFilter(javax.swing.filechooser.FileFilter) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) Component(java.awt.Component) Cursor(java.awt.Cursor) PCGFile(pcgen.io.PCGFile) File(java.io.File)

Example 40 with FileNameExtensionFilter

use of javax.swing.filechooser.FileNameExtensionFilter in project pcgen by PCGen.

the class PCGTrackerPlugin method savePC.

/**
	 * Checks whether a character can be saved, and if so, calls
	 * it's {@code save} method.
	 *
	 * @param aPC The PlayerCharacter to save
	 * @param saveas boolean if {@code true}, ask for file name
	 *
	 * @return {@code true} if saved; {@code false} if save as cancelled
	 */
// TODO use pcgen save methods rather than implementing it again
private boolean savePC(PlayerCharacter aPC, boolean saveas) {
    boolean newPC = false;
    File prevFile;
    File file = null;
    String aPCFileName = aPC.getFileName();
    if (aPCFileName.isEmpty()) {
        prevFile = new File(PCGenSettings.getPcgDir(), aPC.getDisplay().getDisplayName() + Constants.EXTENSION_CHARACTER_FILE);
        aPCFileName = prevFile.getAbsolutePath();
        newPC = true;
    } else {
        prevFile = new File(aPCFileName);
    }
    if (saveas || newPC) {
        JFileChooser fc = ImagePreview.decorateWithImagePreview(new JFileChooser());
        String[] pcgs = { FILENAME_PCG };
        FileFilter ff = new FileNameExtensionFilter(LanguageBundle.getString("in_pcgen_file_char"), //$NON-NLS-1$
        pcgs);
        fc.setFileFilter(ff);
        fc.setSelectedFile(prevFile);
        PropertyChangeListener listener = new FilenameChangeListener(aPCFileName, fc);
        fc.addPropertyChangeListener(listener);
        int returnVal = fc.showSaveDialog(GMGenSystem.inst);
        fc.removePropertyChangeListener(listener);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            if (!PCGFile.isPCGenCharacterFile(file)) {
                file = new File(file.getParent(), file.getName() + Constants.EXTENSION_CHARACTER_FILE);
            }
            if (file.isDirectory()) {
                JOptionPane.showMessageDialog(null, //$NON-NLS-1$
                LanguageBundle.getString("in_savePcDirOverwrite"), Constants.APPLICATION_NAME, JOptionPane.ERROR_MESSAGE);
                return false;
            }
            if (file.exists() && (newPC || !file.getName().equals(prevFile.getName()))) {
                int reallyClose = JOptionPane.showConfirmDialog(GMGenSystem.inst, //$NON-NLS-1$
                LanguageBundle.getFormattedString(//$NON-NLS-1$
                "in_savePcConfirmOverMsg", file.getName()), //$NON-NLS-1$
                LanguageBundle.getFormattedString("in_savePcConfirmOverTitle", file.getName()), JOptionPane.YES_NO_OPTION);
                if (reallyClose != JOptionPane.YES_OPTION) {
                    return false;
                }
            }
            aPC.setFileName(file.getAbsolutePath());
        } else {
            return false;
        }
    } else {
        // simple save
        file = prevFile;
    }
    try {
        (new PCGIOHandler()).write(aPC, null, null, file);
    } catch (Exception ex) {
        //$NON-NLS-1$
        String formattedString = LanguageBundle.getFormattedString("in_saveFailMsg", aPC.getDisplay().getDisplayName());
        JOptionPane.showMessageDialog(null, formattedString, Constants.APPLICATION_NAME, JOptionPane.ERROR_MESSAGE);
        Logging.errorPrint(formattedString);
        Logging.errorPrint(ex.getMessage(), ex);
        return false;
    }
    return true;
}
Also used : PCGIOHandler(pcgen.io.PCGIOHandler) JFileChooser(javax.swing.JFileChooser) PropertyChangeListener(java.beans.PropertyChangeListener) FileFilter(javax.swing.filechooser.FileFilter) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) PCGFile(pcgen.io.PCGFile) File(java.io.File)

Aggregations

FileNameExtensionFilter (javax.swing.filechooser.FileNameExtensionFilter)51 File (java.io.File)31 JFileChooser (javax.swing.JFileChooser)29 FileFilter (javax.swing.filechooser.FileFilter)15 IOException (java.io.IOException)11 Preferences (java.util.prefs.Preferences)7 FileNotFoundException (java.io.FileNotFoundException)6 PCGFile (pcgen.io.PCGFile)6 ResourceBundle (java.util.ResourceBundle)5 SwingWorker (javax.swing.SwingWorker)5 FileOutputStream (java.io.FileOutputStream)3 PCGenSettings (pcgen.system.PCGenSettings)3 ImportException (dr.evolution.io.Importer.ImportException)2 MissingBlockException (dr.evolution.io.NexusImporter.MissingBlockException)2 java.awt (java.awt)2 BorderLayout (java.awt.BorderLayout)2 Cursor (java.awt.Cursor)2 Dimension (java.awt.Dimension)2 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2