簡體   English   中英

如何在JTextArea中保存已編輯的文本文件?

[英]How to save an edited text file in a 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!!!

    }
}

解決此問題的一種方法是更改​​窗口關閉的默認行為,並添加一個捕獲窗口關閉事件的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());就能獲得正確的輸出writer.write(theText.getText()); 不過,主要的好處應該是使用WindowAdapter。

一些相關文檔:

如何編寫窗口偵聽器

這是使用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);
    }
}

暫無
暫無

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

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