有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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!!!

    }
}

共 (2) 个答案

  1. # 1 楼答案

    处理此问题的一种方法是更改窗口关闭的默认行为,并添加一个WindowListener,用于捕获窗口关闭事件并在那里进行保存

    可以添加到DisplayPanel类中的一个简单示例(在创建jFrame对象之后):

        theFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        theFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                String[] lines = theText.getText().split("\\n");
                try (BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt"))) {
                    for (String line : lines)
                        writer.write(line + "\n");
                } catch (IOException i) {
                    System.out.println("Cannot write file...");
                }
    
                System.out.println("File saved!");
                System.exit(0);
            }
        });
    

    当窗口关闭时,上面的代码将把修改后的文本保存到文件newfile.txt

    在上面的例子中,拆分成行可能是不必要的;只需执行writer.write(theText.getText());即可获得正确的输出。不过,主要的收获应该是使用WindowAdapter

    一些相关文件:

    How to Write Window Listeners

  2. # 2 楼答案

    下面是一个使用JButton触发事件来保存文本文件的示例

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    import java.io.*;
    
    public class DisplayPanel {
    
        public static String textFilePath = // adjust path as needed
                "C:\\Users\\Andrew\\Documents\\junk.txt";
        private JComponent ui = null;
        private JFrame frame;
        private JTextArea theText;
        private JButton saveButton;
        private ActionListener actionListener;
        File file;
    
        DisplayPanel(File file) {
            this.file = file;
            try {
                initUI();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    
        private void saveText() {
            Writer writer = null;
            try {
                writer = new FileWriter(file);
                theText.write(writer);
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    writer.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    
        public final void initUI() throws FileNotFoundException, IOException {
            if (ui != null) {
                return;
            }
    
            ui = new JPanel(new BorderLayout(4, 4));
            ui.setBorder(new EmptyBorder(4, 4, 4, 4));
    
            theText = new JTextArea(20, 120); //120 monospaced chrs
            theText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
            theText.setLineWrap(true);
            theText.setEditable(true);
            JScrollPane scroll = new JScrollPane(theText);
            scroll.setVerticalScrollBarPolicy(
                    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    
            ui.add(scroll);
    
            saveButton = new JButton("Save");
            ui.add(saveButton, BorderLayout.PAGE_START);
    
            actionListener = (ActionEvent e) -> {
                saveText();
            };
            saveButton.addActionListener(actionListener);
    
            Reader reader = new FileReader(file);
            theText.read(reader, file);
        }
    
        public void createAndShowGUI() {
            frame = new JFrame(this.getClass().getSimpleName());
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationByPlatform(true);
    
            frame.setContentPane(getUI());
            frame.pack();
            frame.setMinimumSize(frame.getSize());
    
            frame.setVisible(true);
        }
    
        public JComponent getUI() {
            return ui;
        }
    
        public static void main(String[] args) {
            Runnable r = () -> {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                File file = new File(textFilePath);
                DisplayPanel o = new DisplayPanel(file);
                o.createAndShowGUI();
            };
            SwingUtilities.invokeLater(r);
        }
    }