Não consigo criar Botão Salvar no java Aplicativos desktop. Me ajude

3 respostas
G

Não estou conseguindo criar um botão para salvar o texto do jTextArea. Ele até salva mais não com a extenção .txt
Estou fazendo um estilo bloco de notas. Queria uma ajuda com esse pequeno probleminha

[color=red]Esse é o InversorView[/color]
public Task saveAs() {
       // JFileChooser fc = createFileChooser("saveAsFileChooser");
        int option = fc.showSaveDialog(getFrame());
        Task task = null;
        if (JFileChooser.APPROVE_OPTION == option) {
            task = new SaveFileTask(fc.getSelectedFile());
        }
        return task;
    }
    private class SaveAsTask extends org.jdesktop.application.Task<Object, Void> {
        SaveAsTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to SaveAsTask fields, here.
            super(app);
        }
       @Override protected Object doInBackground() {
            // Your Task's code here.  This method runs
            // on a background thread, so don't reference
            // the Swing GUI from here.
           return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    /**
     * A Task that saves the contents of the textArea to the current file.
     * This class is very similar to LoadFileTask, please refer to that
     * class for more information.  
     */
    private class SaveFileTask extends InversorApp.SaveTextFileTask {
        SaveFileTask(File file) {
            super(InversorView.this.getApplication(), file, textArea.getText());
        }

        @Override protected void succeeded(Void ignored) {
	    setFile(getFile());
            setModified(false);
        }

        @Override protected void failed(Throwable e) {
            logger.log(Level.WARNING, "couldn't save " + getFile(), e);
            String msg = getResourceMap().getString("saveFailedMessage", getFile());
            String title = getResourceMap().getString("saveFailedTitle");
            int type = JOptionPane.ERROR_MESSAGE;
            JOptionPane.showMessageDialog(getFrame(), msg, title, type);

So que esse é no

[color=red]InversorApp[/color]
static class SaveTextFileTask extends Task<Void, Void> {

        private final File file;
        private final String text;

        /**
         * Construct a SaveTextFileTask.
         *
         * @param file The file to save to
         * @param text The new contents of the file
         */
        SaveTextFileTask(Application app, File file, String text) {
            super(app);
            this.file = file;
            this.text = text;
        }

        /**
         * Return the File that the {@link #getText text} will be
         * written to.
         *
         * @return the value of the read-only file property.
         */
        public final File getFile() {
            return file;
        }

        /**
         * Return the String that will be written to the
         * {@link #getFile file}.
         *
         * @return the value of the read-only text property.
         */
        public final String getText() {
            return text;
        }

        private void renameFile(File oldFile, File newFile) throws IOException {
            if (!oldFile.renameTo(newFile)) {
                String fmt = "file rename failed: %s => %s";
                throw new IOException(String.format(fmt, oldFile, newFile));
            }
        }

        /**
         * Writes the {@code text} to the specified {@code file}.  The
         * implementation is conservative: the {@code text} is initially
         * written to ${file}.tmp, then the original file is renamed
         * ${file}.bak, and finally the temporary file is renamed to ${file}.
         * The Task's {@code progress} property is updated as the text is
         * written.
         * <p>
         * If this Task is cancelled before writing the temporary file
         * has been completed, ${file.tmp} is deleted.
         * <p>
         * The conservative algorithm for saving to a file was lifted from
         * the FileSaver class described by Ian Darwin here:
         * <a href="http://javacook.darwinsys.com/new_recipes/10saveuserdata.jsp">
         * http://javacook.darwinsys.com/new_recipes/10saveuserdata.jsp
         * </a>.
         *
         * @return null
         */
        @Override
        protected Void doInBackground() throws IOException {
            String absPath = file.getAbsolutePath();
            File tmpFile = new File(absPath + ".tmp");
            tmpFile.createNewFile();
            tmpFile.deleteOnExit();
            File backupFile = new File(absPath + ".bak");
            BufferedWriter out = null;
            int fileLength = text.length();
            int blockSize = Math.max(1024, 1 + ((fileLength - 1) / 100));
            try {
                out = new BufferedWriter(new FileWriter(tmpFile));
                int offset = 0;
                while (!isCancelled() && (offset < fileLength)) {
                    int length = Math.min(blockSize, fileLength - offset);
                    out.write(text, offset, length);
                    offset += blockSize;
                    setProgress(Math.min(offset, fileLength), 0, fileLength);
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            if (!isCancelled()) {
                backupFile.delete();
                if (file.exists()) {
                   renameFile(file, backupFile);
                }
                renameFile(tmpFile, file);
            } else {
                tmpFile.delete();
            }
            return null;
        }
    }

Oq ta de errado q ele não salva com a extenção .txt ?

3 Respostas

Eric_Yuzo

Pelo que eu entendi está sendo criado um arquivo com a extensão “.bak” não é isso?

File backupFile = new File(absPath + ".bak");Especifique a extensão “.txt” quando for nomear o arquivo.

File backupFile = new File(absPath + ".txt");
G

Ele salva sem nenhuma extensão

Se alguem tiver um codigo me passe por favor

G

public Task saveAs() { // JFileChooser fc = createFileChooser("saveAsFileChooser"); int option = Salvejf.showSaveDialog(getFrame()); Task task = null; if (JFileChooser.APPROVE_OPTION == option) { task = new SaveFileTask(Salvejf.getSelectedFile()); } return task; } private class SaveAsTask extends org.jdesktop.application.Task<Object, Void> { SaveAsTask(org.jdesktop.application.Application app) {

sera q é aq

Criado 4 de outubro de 2010
Ultima resposta 5 de out. de 2010
Respostas 3
Participantes 2