21xrx.com
2025-04-26 21:24:38 Saturday
文章检索 我的文章 写文章
Java代码实现一个简单文本编辑器
2023-06-17 00:23:14 深夜i     9     0
Java代码 文本编辑器 打开文件 保存文件

在日常生活中,对于常使用的文本编辑器,我们可能会使用Microsoft Office Word、Notepad++、Sublime Text等软件。但如果只需要实现基础的文本编辑功能,我们也可以通过编写Java代码来实现一个简单的文本编辑器。

以下是一份基础的Java代码实现:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextEditor extends JFrame implements ActionListener {
  private static final long serialVersionUID = 1L;
  private JTextArea textArea;
  private JFileChooser chooseFile;
  public TextEditor() {
    super("Java文本编辑器");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(800, 600);
    setLocationRelativeTo(null);
    //设置文本编辑区
    textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(scrollPane, BorderLayout.CENTER);
    //设置按钮
    JPanel buttonPanel = new JPanel();
    add(buttonPanel, BorderLayout.SOUTH);
    JButton openButton = new JButton("打开");
    openButton.addActionListener(this);
    buttonPanel.add(openButton);
    JButton saveButton = new JButton("保存");
    saveButton.addActionListener(this);
    buttonPanel.add(saveButton);
    chooseFile = new JFileChooser();
    setVisible(true);
  }
  public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    // 处理打开文件事件
    if (command.equals("打开")) {
      int result = chooseFile.showOpenDialog(this);
      if (result == JFileChooser.APPROVE_OPTION) {
        String fileContent = "";
        String filePath = chooseFile.getSelectedFile().getPath();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
          String line = "";
          while ((line = reader.readLine()) != null) {
            fileContent += line + "\n";
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
        textArea.setText(fileContent);
      }
    }
    // 处理保存文件事件
    if (command.equals("保存")) {
      int result = chooseFile.showSaveDialog(this);
      if (result == JFileChooser.APPROVE_OPTION) {
        String filePath = chooseFile.getSelectedFile().getPath();
        try (FileWriter writer = new FileWriter(filePath)) {
          writer.write(textArea.getText());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  public static void main(String[] args) {
    new TextEditor();
  }
}

这个文本编辑器实现了打开和保存文件的功能,并在文本编辑区展示文件中的内容。

  
  

评论区