Como salvar um texto digitado no JTextArea?

Fiz um simples editor de Texto conforme o exercício do livro "Big Java" utilizando o NetBeans porêm não faço idéia de como salvar em .txt um arquivo, podem fornecer a solução, exemplo, em fim qualquer coisa para ajudar??

/*
 * UmEditorDetextosimplesView.java
 */

package umeditordetextosimples;

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 UmEditorDetextosimplesView extends FrameView {

    public UmEditorDetextosimplesView(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 = UmEditorDetextosimplesApp.getApplication().getMainFrame();
            aboutBox = new UmEditorDetextosimplesAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        UmEditorDetextosimplesApp.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();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = 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(umeditordetextosimples.UmEditorDetextosimplesApp.class).getContext().getResourceMap(UmEditorDetextosimplesView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

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

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, 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_L, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        fileMenu.add(jMenuItem2);

        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) {
if (jFileChooser1 == null) {
    
        
            

        }
        UmEditorDetextosimplesApp.getApplication().show(aboutBox);


			       // TODO add your handling code here:
    }

    // 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;
}
/*
 * UmEditorDetextosimplesAboutBox.java
 */

package umeditordetextosimples;

import org.jdesktop.application.Action;

public class UmEditorDetextosimplesAboutBox extends javax.swing.JDialog {

    public UmEditorDetextosimplesAboutBox(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 imageLabel = new javax.swing.JLabel();

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

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(umeditordetextosimples.UmEditorDetextosimplesApp.class).getContext().getActionMap(UmEditorDetextosimplesAboutBox.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

        imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N
        imageLabel.setName("imageLabel"); // 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()
                .addComponent(imageLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(closeButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 183, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(appTitleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                .addComponent(closeButton)
                .addContainerGap())
        );

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

/*
 * UmEditorDetextosimplesApp.java
 */

package umeditordetextosimples;

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

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

    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        show(new UmEditorDetextosimplesView(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 UmEditorDetextosimplesApp
     */
    public static UmEditorDetextosimplesApp getApplication() {
        return Application.getInstance(UmEditorDetextosimplesApp.class);
    }

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

============================================================

Alterado de JTextField para Area porque me confundi

Olá… :smiley:

Não fiquei olhgando como está o seu texto no editor… mas vamos supor que o editor gera uma String :stuck_out_tongue: e precisa de um método para gravar, vamos lá:

[code]
public void Gravar(String texto, String nomeArq) throws IOException
{
FileOutputStream out;

  PrintStream p;   
     
  try  
  {   
     out = new FileOutputStream("seu path" +nomeArq+".txt", false); // Para não sobreescrever, deixe true.

     out.println();  // Linha em branco.
     
     p = new PrintStream(out);   
        
     p.write(texto);   
     
     p.close();   
  }   
  catch(Exception e)      
  {   
     System.err.println(e);   
  }      

}
[/code]Sei que é o mínimo e que você mesmo já deve conhecer… mas fica aí minha ajudinha :smiley: Até +…

[quote=ingridfarabulini]Olá… :smiley:

Não fiquei olhgando como está o seu texto no editor… mas vamos supor que o editor gera uma String :stuck_out_tongue: e precisa de um método para gravar, vamos lá:

[code]
public void Gravar(String texto, String nomeArq) throws IOException
{
FileOutputStream out;

  PrintStream p;   
     
  try  
  {   
     out = new FileOutputStream("seu path" +nomeArq+".txt", false); // Para não sobreescrever, deixe true.

     out.println();  // Linha em branco.
     
     p = new PrintStream(out);   
        
     p.write(texto);   
     
     p.close();   
  }   
  catch(Exception e)      
  {   
     System.err.println(e);   
  }      

}
[/code]Sei que é o mínimo e que você mesmo já deve conhecer… mas fica aí minha ajudinha :smiley: Até +…[/quote]

aparentemente seu código não funciona e não entendi como posso gravar um texto com isto??

Eu quero gravar usando um jFileChooser1 em um arquivo.txt.

Não funcionou ?? :roll: Estranho…
Qual o problema que ocorreu, pode me informar?
Até +…

[quote=ingridfarabulini]Não funcionou ?? :roll: Estranho…
Qual o problema que ocorreu, pode me informar?
Até +…[/quote]

Além de não entender nada de como ele salva um texto em .txt, este método não abre o jFileChooser1 como dito e nem salva o arquivo.

Fico imaginando, esta difícil apenas salvar um arquivo em .txt, tenho um longo caminho…

Acho que entendeu como se eu quisesse que o valor da JTextArea fosse para uma String, se fosse só isto era só um getText();

[quote=DarthVictor][quote=ingridfarabulini]Não funcionou ?? :roll: Estranho…
Qual o problema que ocorreu, pode me informar?
Até +…[/quote]

Além de não entender nada de como ele salva um texto em .txt, este método não abre o jFileChooser1 como dito e nem salva o arquivo.

Fico imaginando, esta difícil apenas salvar um arquivo em .txt, tenho um longo caminho…

Acho que entendeu como se eu quisesse que o valor da JTextArea fosse para uma String, se fosse só isto era só um getText();[/quote]
:smiley: … Moço a princípio entendi que precisava fazer o que está no título da sua primeira postagem: “Como salvar um texto digitado no JTextField ??”
Se é isso, o código acima funciona sim, pelo menos aqui funcionou. :roll:

Lá onde está escrito ‘seu path’ é o local onde você vai informar o caminho para salvar o seu arquivo, entendeu?
O nome e o texto você passa ao método, conforme a assinatura, você está entendendo?

Agora usar o JFileChooser é outra coisa… 8) Eu preciso estudar para aprender…

Até +…