如果我在JTextArea中输入文本并单击"保存"按钮,JTextArea文本应写入/保存到.txt文件中。是我的尝试&捕获在事件处理程序方法中的正确位置,或者它的部分应该在构造函数中?
这是我的代码:
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();
}
}
}
}
提前致谢
答案 0 :(得分:1)
您的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);
(this
是SimpleNotePadApp
实例,它实现ActionListener
)
最后,你需要:
if(e.getSource() == button2)
...因为button2
是您的“保存”按钮(不是button1
)