java如何在JTextArea中保存编辑过的文本文件?
我正在尝试用Java编写一个文本编辑器应用程序。下面的程序读入一个文本文件,然后通过BufferedReader
方法显示它。然而,在这一点上,我完全被卡住了。可以在JFrame
窗口中编辑显示的文本。但在编辑之后,我不知道如何关闭并保存已编辑的文件(即如何合并事件处理程序,然后保存已编辑的文本)
我已经尝试了很多事情,但是我非常感谢你能帮助我从这一点上取得进展。我对Java非常陌生,所以可能我的程序的整个结构都是错误的-非常感谢任何帮助。主程序在这里,后面是它调用的显示面板创建者。程序应该弹出一个窗口,其中包含您已放置在目录中的名为text.txt
的任何文本文件
主要内容:
import java.io.*;
import java.util.ArrayList;
import static java.lang.System.out;
public class testApp4 {
public static void main(String args[]) {
ArrayList<String> listToSend = new ArrayList<String>();
String file = "text.txt";
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = br.readLine()) != null) {
listToSend.add(line);
}
br.close();
}
catch(FileNotFoundException e)
{
out.println("Cannot find the specified file...");
}
catch(IOException i)
{
out.println("Cannot read file...");
}
new DisplayPanel(listToSend);
}
}
显示面板创建者:
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;// javax.swing.*;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class DisplayPanel {
public DisplayPanel(ArrayList<String> list) //constructor of the DisplayGuiHelp object that has the list passed to it on creation
{
JTextArea theText = new JTextArea(46,120); //120 monospaced chrs
theText.setFont(new Font("monospaced", Font.PLAIN, 14));
theText.setLineWrap(true);
theText.setEditable(true);
for(String text : list)
{
theText.append(text + "\n"); //append the contents of the array list to the text area
}
JScrollPane scroll = new JScrollPane(theText);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel mainPanel = new JPanel();
mainPanel.add(scroll);
final JFrame theFrame = new JFrame();
theFrame.setTitle("textTastico");
theFrame.setSize(1100, 1000);
theFrame.setLocation(550, 25);
theFrame.add(mainPanel); //add the panel to the frame
theFrame.setVisible(true);
System.out.print(theText.getText()); //double check output!!!
}
}
# 1 楼答案
处理此问题的一种方法是更改窗口关闭的默认行为,并添加一个WindowListener,用于捕获窗口关闭事件并在那里进行保存
可以添加到DisplayPanel类中的一个简单示例(在创建jFrame对象之后):
当窗口关闭时,上面的代码将把修改后的文本保存到文件
newfile.txt
在上面的例子中,拆分成行可能是不必要的;只需执行
writer.write(theText.getText());
即可获得正确的输出。不过,主要的收获应该是使用WindowAdapter一些相关文件:
How to Write Window Listeners
# 2 楼答案
下面是一个使用
JButton
触发事件来保存文本文件的示例