📜  Java摇摆 |创建一个简单的文本编辑器

📅  最后修改于: 2022-05-13 01:54:43.176000             🧑  作者: Mango

Java摇摆 |创建一个简单的文本编辑器

为了在Java Swing 中创建一个简单的文本编辑器,我们将使用 JTextArea、JMenuBar 并向其中添加 JMenu,我们将添加 JMenuItems。所有的菜单项都会有 actionListener 来检测任何动作。
将有一个菜单栏,它将包含两个菜单和一个按钮:

  1. 文件菜单
    • open : 此菜单项用于打开文件
    • save :此菜单项用于保存文件
    • print :此菜单项用于打印文本区域的组件
    • new : 这个菜单项用于创建一个新的空白文件
  2. 编辑菜单
    • cut :此菜单项用于剪切选定区域并将其复制到剪贴板
    • 复制:此菜单项是将选定区域复制到剪贴板
    • paste :此菜单项是将剪贴板中的文本粘贴到文本区域
  3. 关闭:此按钮关闭框架

我们使用了文件阅读器和文件编写器来获取更多关于Java文件读写的信息。请点击以下链接:

  • Java中读取文本文件的不同方法
  • 使用 FileWriter 和 FileReader 在Java中处理文件

使用的方法:

methodexplanation
cut()removes the selected area from the text area and store it in clipboard
copy()copies the selected area from the text area and store it in clipboard
paste()removes the selected area from the text area and store it in clipboard
print()prints the components of the text area

有关 JSwing 组件的更多方法,请参阅:

  1. Java摇摆 |面板
  2. Java摇摆 |菜单栏
  3. 在Java中使用 Swings 创建框架
  4. Java摇摆 |文本区域

创建简单文本编辑器的程序:
创建一个简单的文本编辑器:

  • 首先,我们将创建一个名为“editor”的框架并应用金属外观并在其中设置海洋主题。
  • 我们将添加一个文本区域和一个菜单栏,其中包含三个菜单文件、编辑和关闭。
    • “文件”选项有 4 个新菜单项,打开、保存和打印。
    • “编辑”有 3 个菜单项剪切、复制和粘贴。我们将为所有菜单项添加一个动作侦听器(使用 addActionListener()函数)以检测任何动作。
  • 我们将使用 add()函数将菜单项添加到菜单和菜单栏,我们将使用 addJMenuBar()函数将菜单栏添加到框架。
  • 我们将使用 add函数将文本区域添加到框架中,使用 setSize(500,500)函数将框架的大小设置为 500,500,然后使用 show函数显示框架。

以下是菜单功能的调用方式:

  • 在选择剪切、复制、粘贴和打印菜单项时,将调用文本区域 cut()、copy()、paste() 和 print() 的内置函数。
  • 选择“保存”菜单项时,将打开一个文件选择器,在选择文件后将显示保存对话框,文件写入器(缓冲写入器)会将文本区域的内容写入文件并关闭文件写入器和缓冲写入器。
  • 在选择“打开”菜单项时,将打开一个文件选择器,在选择文件后将显示打开对话框,文件阅读器和缓冲阅读器将读取文件并将文本区域的文本设置为文件的内容。
  • 如果选择“新”菜单项,则文本区域的文本将设置为空白。如果选择“关闭”菜单项,则使用函数isVisible(false) 关闭框架。

程序:

Java
// Java Program to create a text editor using java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;
class editor extends JFrame implements ActionListener {
    // Text component
    JTextArea t;
 
    // Frame
    JFrame f;
 
    // Constructor
    editor()
    {
        // Create a frame
        f = new JFrame("editor");
 
        try {
            // Set metal look and feel
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
 
            // Set theme to ocean
            MetalLookAndFeel.setCurrentTheme(new OceanTheme());
        }
        catch (Exception e) {
        }
 
        // Text component
        t = new JTextArea();
 
        // Create a menubar
        JMenuBar mb = new JMenuBar();
 
        // Create amenu for menu
        JMenu m1 = new JMenu("File");
 
        // Create menu items
        JMenuItem mi1 = new JMenuItem("New");
        JMenuItem mi2 = new JMenuItem("Open");
        JMenuItem mi3 = new JMenuItem("Save");
        JMenuItem mi9 = new JMenuItem("Print");
 
        // Add action listener
        mi1.addActionListener(this);
        mi2.addActionListener(this);
        mi3.addActionListener(this);
        mi9.addActionListener(this);
 
        m1.add(mi1);
        m1.add(mi2);
        m1.add(mi3);
        m1.add(mi9);
 
        // Create amenu for menu
        JMenu m2 = new JMenu("Edit");
 
        // Create menu items
        JMenuItem mi4 = new JMenuItem("cut");
        JMenuItem mi5 = new JMenuItem("copy");
        JMenuItem mi6 = new JMenuItem("paste");
 
        // Add action listener
        mi4.addActionListener(this);
        mi5.addActionListener(this);
        mi6.addActionListener(this);
 
        m2.add(mi4);
        m2.add(mi5);
        m2.add(mi6);
 
        JMenuItem mc = new JMenuItem("close");
 
        mc.addActionListener(this);
 
        mb.add(m1);
        mb.add(m2);
        mb.add(mc);
 
        f.setJMenuBar(mb);
        f.add(t);
        f.setSize(500, 500);
        f.show();
    }
 
    // If a button is pressed
    public void actionPerformed(ActionEvent e)
    {
        String s = e.getActionCommand();
 
        if (s.equals("cut")) {
            t.cut();
        }
        else if (s.equals("copy")) {
            t.copy();
        }
        else if (s.equals("paste")) {
            t.paste();
        }
        else if (s.equals("Save")) {
            // Create an object of JFileChooser class
            JFileChooser j = new JFileChooser("f:");
 
            // Invoke the showsSaveDialog function to show the save dialog
            int r = j.showSaveDialog(null);
 
            if (r == JFileChooser.APPROVE_OPTION) {
 
                // Set the label to the path of the selected directory
                File fi = new File(j.getSelectedFile().getAbsolutePath());
 
                try {
                    // Create a file writer
                    FileWriter wr = new FileWriter(fi, false);
 
                    // Create buffered writer to write
                    BufferedWriter w = new BufferedWriter(wr);
 
                    // Write
                    w.write(t.getText());
 
                    w.flush();
                    w.close();
                }
                catch (Exception evt) {
                    JOptionPane.showMessageDialog(f, evt.getMessage());
                }
            }
            // If the user cancelled the operation
            else
                JOptionPane.showMessageDialog(f, "the user cancelled the operation");
        }
        else if (s.equals("Print")) {
            try {
                // print the file
                t.print();
            }
            catch (Exception evt) {
                JOptionPane.showMessageDialog(f, evt.getMessage());
            }
        }
        else if (s.equals("Open")) {
            // Create an object of JFileChooser class
            JFileChooser j = new JFileChooser("f:");
 
            // Invoke the showsOpenDialog function to show the save dialog
            int r = j.showOpenDialog(null);
 
            // If the user selects a file
            if (r == JFileChooser.APPROVE_OPTION) {
                // Set the label to the path of the selected directory
                File fi = new File(j.getSelectedFile().getAbsolutePath());
 
                try {
                    // String
                    String s1 = "", sl = "";
 
                    // File reader
                    FileReader fr = new FileReader(fi);
 
                    // Buffered reader
                    BufferedReader br = new BufferedReader(fr);
 
                    // Initialize sl
                    sl = br.readLine();
 
                    // Take the input from the file
                    while ((s1 = br.readLine()) != null) {
                        sl = sl + "\n" + s1;
                    }
 
                    // Set the text
                    t.setText(sl);
                }
                catch (Exception evt) {
                    JOptionPane.showMessageDialog(f, evt.getMessage());
                }
            }
            // If the user cancelled the operation
            else
                JOptionPane.showMessageDialog(f, "the user cancelled the operation");
        }
        else if (s.equals("New")) {
            t.setText("");
        }
        else if (s.equals("close")) {
            f.setVisible(false);
        }
    }
 
    // Main class
    public static void main(String args[])
    {
        editor e = new editor();
    }
}


输出:

注意:以上程序可能无法在在线 IDE 中运行,请使用离线编译器。