[Resolvido]Salvar um arquivo por uma jFileChooser. como faço?

3 respostas
D

Alguém ai sabe como faço para salvar, pois tenho de fazer um editor de texto e um editor de texto não serve para nada se eu não puder salvar e abrir arquivos.

Qualquer exemplo de código ou tutorial para mim, serve.

Agradeço desde já

E se quiserem ver o notepad que estou fazendo no netBeans, é só ler o código abaixo.

/*
 * MyNotepadApp.java
 */

package mynotepad;

import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * The main class of the application.
 */
public class MyNotepadApp extends SingleFrameApplication {

    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        show(new MyNotepadView(this));
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of MyNotepadApp
     */
    public static MyNotepadApp getApplication() {
        return Application.getInstance(MyNotepadApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(MyNotepadApp.class, args);
    }
}
/*
 * MyNotepadAboutBox.java
 */

package mynotepad;

import org.jdesktop.application.Action;

public class MyNotepadAboutBox extends javax.swing.JDialog {

    public MyNotepadAboutBox(java.awt.Frame parent) {
        super(parent);
        initComponents();
        getRootPane().setDefaultButton(closeButton);
    }

    @Action public void closeAboutBox() {
        dispose();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        closeButton = new javax.swing.JButton();
        javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
        javax.swing.JLabel appDescLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(mynotepad.MyNotepadApp.class).getContext().getResourceMap(MyNotepadAboutBox.class);
        setTitle(resourceMap.getString("title")); // NOI18N
        setModal(true);
        setName("aboutBox"); // NOI18N
        setResizable(false);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(mynotepad.MyNotepadApp.class).getContext().getActionMap(MyNotepadAboutBox.class, this);
        closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N
        closeButton.setName("closeButton"); // NOI18N

        appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
        appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N
        appTitleLabel.setName("appTitleLabel"); // NOI18N

        appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N
        appDescLabel.setName("appDescLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                    .addComponent(closeButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(appTitleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(appDescLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)
                .addComponent(closeButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>
    
    // Variables declaration - do not modify
    private javax.swing.JButton closeButton;
    // End of variables declaration
    
}
/*
 * MyNotepadView.java
 */

package mynotepad;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;

/**
 * The application's main frame.
 */
public class MyNotepadView extends FrameView {

    public MyNotepadView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
   
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
       
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");


        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
 
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
               
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
               
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                 
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = MyNotepadApp.getApplication().getMainFrame();
            aboutBox = new MyNotepadAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        MyNotepadApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        scrollPane1 = new java.awt.ScrollPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        jFileChooser1 = new javax.swing.JFileChooser();

        mainPanel.setName("mainPanel"); // NOI18N

        scrollPane1.setName("scrollPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane1.setViewportView(jTextArea1);

        scrollPane1.add(jScrollPane1);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(mynotepad.MyNotepadApp.class).getContext().getResourceMap(MyNotepadView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem2);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(mynotepad.MyNotepadApp.class).getContext().getActionMap(MyNotepadView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        jFileChooser1.setName("jFileChooser1"); // NOI18N

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1.showDialog(mainPanel, null);
    }

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1.showDialog(mainPanel, null);
    }

    // Variables declaration - do not modify
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private java.awt.ScrollPane scrollPane1;
    // End of variables declaration

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}

3 Respostas

A

Depende do formato que deseja gravar, no caso em um formato qualquer, ex: .obj

private static void gravaObjeto (File f, Object o){
        try	{
            FileOutputStream fos = new FileOutputStream (f);
            ObjectOutputStream os = new ObjectOutputStream (fos);
            os.writeObject (o);
            os.close ();
        }catch (IOException e)  {
                System.out.println ("Erro ao gravar objeto.");
        }
    }
else if(e.getSource() == save){
                            Object c = new Object();
	            int returnVal = fc.showSaveDialog(PanelPrincipal.this);
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fc.getSelectedFile();
	                File f = new File(file+".obj");
	                gravaObjeto(f, c);
	                
	            }
	        }

Para gravar a classe do objeto tem que implementar a Serializable.

D

Allan Barcelos:
Depende do formato que deseja gravar, no caso em um formato qualquer, ex: .obj

private static void gravaObjeto (File f, Object o){
        try	{
            FileOutputStream fos = new FileOutputStream (f);
            ObjectOutputStream os = new ObjectOutputStream (fos);
            os.writeObject (o);
            os.close ();
        }catch (IOException e)  {
                System.out.println ("Erro ao gravar objeto.");
        }
    }
else if(e.getSource() == save){
                            Object c = new Object();
	            int returnVal = fc.showSaveDialog(PanelPrincipal.this);
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fc.getSelectedFile();
	                File f = new File(file+".obj");
	                gravaObjeto(f, c);
	                
	            }
	        }

Para gravar a classe do objeto tem que implementar a Serializable.

Como assim implementar “Serializable” e não entendi como o arquivo será gravado em .qualquer coisa, nem onde esta usando o jFileChooser que é o que presiso

A

Calma cara…, o serializable te possibilita salvar um arquivo sólido, mas para isso tem de implementar a Serializable para poder salvar, aqui no site tu pode ter uma ideia http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html . Quanto ao JFileChooser:

Declarando um JFileChooser

JFileChooser fc; // tu pode colocar um modificador ex: private, etc...

Criando um JFileChooser:

fc = new JFileChooser();

Então depois de criado o JFileChooser, tu deve colocar um evento, exemplo quando for carregar um arquivo ou salvar um arquivo

if(se tu clicou em salvar){

		            int returnVal = fc.showSaveDialog(TeuPanel.this);
		            if (returnVal == JFileChooser.APPROVE_OPTION) {
		                File file = fc.getSelectedFile();
		                File f = new File(file); // salva um arquivo solido
		                gravaObjeto(f, c);
		                
		            }
}
if(tu clicou em carregar){
	            int returnVal = fc.showOpenDialog(TeuPanel.this);

	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fc.getSelectedFile();
	                Object c = leObjeto(file);
	            }
	        }

Para ler e gravar um objeto:

private static Object leObjeto (File f){	
    	Object o = null;
		try	{
			FileInputStream fos = new FileInputStream (f);
			ObjectInputStream os = new ObjectInputStream (fos);
			o = os.readObject ();
			os.close ();
		}catch (IOException e) {
			System.out.println ("Erro ao abrir arquivo.");
		}
		catch (ClassNotFoundException ce) {
			System.out.println ("Objeto não encontrado.");
		}
		return o;
	}


    private static void gravaObjeto (File f, Object o){
        try	{
            FileOutputStream fos = new FileOutputStream (f);
            ObjectOutputStream os = new ObjectOutputStream (fos);
            os.writeObject (o);
            os.close ();
        }catch (IOException e)  {
                System.out.println ("Erro ao gravar objeto.");
        }
    }
Criado 17 de junho de 2010
Ultima resposta 18 de jun. de 2010
Respostas 3
Participantes 2