簡體   English   中英

使用按鈕將 JTextArea 保存到 .txt 文件

[英]Saving JTextArea to a .txt file with a button

如果我在 JTextArea 中輸入文本並單擊“保存”按鈕,則 JTextArea 文本應寫入/保存到 .txt 文件中。 我的 try & catch 是在事件處理程序方法中的正確位置還是它的一部分應該在構造函數中?

這是我的代碼:

package exercises;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class SimpleNotePadApp extends JFrame implements ActionListener {

JButton button1 = new JButton("Open");
JButton button2 = new JButton("Save");

public SimpleNotePadApp(String title) {
    super(title);                             
    setDefaultCloseOperation(EXIT_ON_CLOSE);  
    setSize(300, 350);                        
    setLayout(null);


    JTextArea newItemArea = new JTextArea();
    newItemArea.setLocation(3, 3);
    newItemArea.setSize(297, 282);
    getContentPane().add(newItemArea);

    button1.setLocation(30,290);  
    button1.setSize(120, 25);
    getContentPane().add(button1);

    button2.setLocation(150,290);  
    button2.setSize(120, 25);
    getContentPane().add(button2);

}

public static void main(String[] args) {
    SimpleNotePadApp frame;

    frame = new SimpleNotePadApp("Text File GUI");      
    frame.setVisible(true);                             
}

public void actionPerformed(ActionEvent e) {

    if(e.getSource() == button1)
    {
        try {
            PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
            newItemArea.getText();
            newItemArea.write(out);
            out.println(newItemArea);
            out.flush();
            out.close();

        } catch (IOException e1) {
            System.err.println("Error occurred");
            e1.printStackTrace();
        }
    }
}
}

提前致謝

你的try ... catch是在正確的位置,但內容應該是:

        PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt"));
        newItemArea.write(out);
        out.close();

考慮使用 try-with-resources,並且.close()變得不必要:

    try ( PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")) {
        newItemArea.write(out);
    } catch (IOException e1) {
        System.err.println("Error occurred");
        e1.printStackTrace();
    }

此外,您需要在構建過程中將ActionListener附加到JButton

button2.addActionListener(this);

thisSimpleNotePadApp實例,它實現了ActionListener

最后,你會想要:

 if(e.getSource() == button2)

...因為button2是您的“保存”按鈕(不是button1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM