Java实现简易的记事本


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;


import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;


/**
  * 简易编辑器V1,0
  * 
  * @author CGgeeker
  * 
  */
public class Editor02 extends JFrame implements ActionListener {
    JComboBox comboBoxOfFontName, comboBoxOfFontsize;
    JTextArea textArea;
    JCheckBox checkBoxOfFontStylebold, checkBoxOfFontStyleitalic;
    JRadioButton radiobuttonred, radiobuttonblue, radiobuttongreen;
    ButtonGroup buttongroupcolor;
    JPanel panelcolor;
    Clipboard clipboard = getToolkit().getSystemClipboard();


    public Editor02() {
        // 设置窗体标题
        super("简易编辑器V2.0");
        // 获取屏幕分辨率
        Dimension dim = this.getToolkit().getScreenSize();
        // 窗体初始大小及定位
        this.setBounds(dim.width / 4, dim.height / 4, (dim.width / 2 + 40),dim.height / 2);
        // 设置内容面板按边界布局
        this.getContentPane().setLayout(new BorderLayout());
        // 1. 调用自定义方法addMenuBar()设置窗体的菜单栏
        this.addMenuBar();
        // 2. 调用自定义方法addToolBar()添加工具栏到内容面板
        this.addToolBar();
        // 3. 调用自定义方法addTextArea()添加文本区到内容面板
        this.addTextArea();
    }


    /**
     * 设置窗体菜单栏
     */
    private void addMenuBar() {
        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        // 创建“文件”菜单
        JMenu filemenu = new JMenu("文件");
        // 创建“编辑”菜单
        JMenu editormenu = new JMenu("编辑");
        // 创建“帮助”菜单
        JMenu helpmenu = new JMenu("帮助");
        // 创建菜单项
        JMenuItem menuItemOfOpen = new JMenuItem("打开");
        JMenuItem menuItemOfSave = new JMenuItem("保存");
        JMenuItem menuItemOfExit = new JMenuItem("退出");
        JMenuItem menuItemOfCopy = new JMenuItem("复制");
        JMenuItem menuItemOfCut = new JMenuItem("剪切");
        JMenuItem menuItemOfPaste = new JMenuItem("粘贴");
        JMenuItem menuItemOfDelete = new JMenuItem("删除");
        JMenuItem menuItemOfHelpexplanation = new JMenuItem("帮助说明");
        // 给各个菜单项注册单击事件侦听器
        menuItemOfOpen.addActionListener(this);
        menuItemOfSave.addActionListener(this);
        menuItemOfExit.addActionListener(this);
        menuItemOfCopy.addActionListener(this);
        menuItemOfCut.addActionListener(this);
        menuItemOfPaste.addActionListener(this);
        menuItemOfDelete.addActionListener(this);
        menuItemOfHelpexplanation.addActionListener(new ActionListener() {
            /**
             * 帮助窗体(弹窗)
             */
            @Override
            public void actionPerformed(ActionEvent e) {
                String separator = System.getProperty("line.separator");// 获得系统默认的分隔符-固定写法(写死了的!)
                final JFrame helpjframe = new JFrame("帮助说明");
                helpjframe.setBounds(410, 250, 600, 320);
                helpjframe.setVisible(true);
                helpjframe.setLayout(new BorderLayout());
                TextArea helpjframetextArea = new TextArea();
                helpjframetextArea.setText("该文本功能如下:" + separator + separator
                        + "1.实现基本的TXT文件保存和打开" + separator + separator
                        + "2.实现基本的剪辑,复制,粘贴,删除功能" + separator + separator
                        + "3.实现基本的字体处理操作!");
                helpjframetextArea.setForeground(getForeground().blue); // 设置前景色(字体的颜色)
                helpjframetextArea.setFont(new Font(null, HEIGHT, 26)); // 设置字体大小,样式
                JButton helpjframeButton = new JButton("退出");

                helpjframe.add(helpjframetextArea);
                helpjframe.add(helpjframeButton);

                helpjframe.add(helpjframetextArea, "Center"); // 简单布局
                helpjframe.add(helpjframeButton, "South");
                helpjframeButton.addActionListener(new ActionListener() {
                    // 实现对“帮助说明”窗体中的“退出”按钮的监听事件处理
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (JOptionPane.showConfirmDialog(helpjframe, "是否退出?") == 0) {
                            helpjframe.setVisible(false);
                        }
                    }
                });
            }
        });
        // 给文本域添加鼠标监听器

        // 菜单项加到"文件"菜单
        filemenu.add(menuItemOfOpen);
        filemenu.add(menuItemOfSave);
        filemenu.addSeparator(); // 添加分隔线
        filemenu.add(menuItemOfExit);
        // 菜单项加到"编辑"菜单
        editormenu.add(menuItemOfCopy);
        editormenu.add(menuItemOfCut);
        editormenu.add(menuItemOfPaste);
        editormenu.add(menuItemOfDelete);
        // 菜单项添加到"帮助"菜单
        helpmenu.add(menuItemOfHelpexplanation);
        // 将"文件"菜单,"编辑"菜单,"帮助"菜单加到菜单栏
        menuBar.add(filemenu);
        menuBar.add(editormenu);
        menuBar.add(helpmenu);
        // 设置窗体的菜单栏
        this.setJMenuBar(menuBar);
    }
    /**
     * 添加工具栏
     */
    private void addToolBar() {
        // 创建工具栏
        JToolBar toolBar = new JToolBar();
        // 设置工具栏的布局
        toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
        // 获取系统字体名字
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String fontNames[] = ge.getAvailableFontFamilyNames();
        // 设置文字大小数组
        String fontsizeNames[] = { "20", "23", "26", "29", "32", "35", "38","42" };
        // 创建“字体”标签
        Label fontlabel = new Label("字体:");
        // 创建“大小”标签
        Label fontsizelabel = new Label("大小:");
        // 创建“风格”标签
        Label fontstyle = new Label("风格:");
        // 创建“颜色”标签
        Label fontcolor = new Label("颜色:");
        // 创建字体组合框
        comboBoxOfFontName = new JComboBox(fontNames);
        // 创建字体大小组合框
        comboBoxOfFontsize = new JComboBox(fontsizeNames);
        // 创建字体风格复选框
        checkBoxOfFontStylebold = new JCheckBox("粗体");
        checkBoxOfFontStyleitalic = new JCheckBox("斜体");
        // 创建颜色面板
        panelcolor = new JPanel();
        // 创建颜色按钮组
        buttongroupcolor = new ButtonGroup();
        // 创建字体颜色单选按钮
        radiobuttonred = new JRadioButton("红");
        radiobuttonblue = new JRadioButton("蓝");
        radiobuttongreen = new JRadioButton("绿");
        // 字体组合框注册单击事件侦听器
        comboBoxOfFontName.addActionListener(this);
        // 字体大小组合框注册单击事件监听器
        comboBoxOfFontsize.addActionListener(this);
        // 给复选框注册单击事件监听器
        checkBoxOfFontStylebold.addActionListener(this);
        checkBoxOfFontStyleitalic.addActionListener(this);
        // 给单选按钮注册单击事件监听器
        radiobuttonred.addActionListener(this);
        radiobuttonblue.addActionListener(this);
        radiobuttongreen.addActionListener(this);
        // 在字体组合框中添加“字体”标签
        toolBar.add(fontlabel);
        // 字体组合框加到工具栏
        toolBar.add(comboBoxOfFontName);
        // 在字体大小组合框中加“大小”标签
        toolBar.add(fontsizelabel);
        // 字体大小组合框加到工具栏
        toolBar.add(comboBoxOfFontsize);
        // 给复选框添加“风格”标签
        toolBar.add(fontstyle);
        // 字体风格复选框加到工具栏
        toolBar.add(checkBoxOfFontStylebold);
        toolBar.add(checkBoxOfFontStyleitalic);
        // 给单选框添加“颜色”标签
        toolBar.add(fontcolor);
        // 字体颜色单选按钮加到颜色按钮组中
        buttongroupcolor.add(radiobuttonred);
        buttongroupcolor.add(radiobuttonblue);
        buttongroupcolor.add(radiobuttongreen);
        // 往面板中加入单选按钮
        panelcolor.add(radiobuttonred);
        panelcolor.add(radiobuttonblue);
        panelcolor.add(radiobuttongreen);
        // 颜色按钮组加到工具栏
        toolBar.add(panelcolor);
        // 工具栏加到内容面板北边
        this.getContentPane().add(toolBar, "North");
    }


    /**
     * 添加文本区
     */
    private void addTextArea() {
        textArea = new JTextArea("欢迎来到我的世界,上帝你好!");
        textArea.setLineWrap(true); // 设置文本域为自动换行
        textArea.setBackground(getBackground().pink); // 给文本域设置背景颜色为粉红
        JScrollPane textareascrollPane = new JScrollPane(textArea); // 将文本域添加到含有下拉框(条)的面板中
        this.getContentPane().add(textareascrollPane); // 将含有下拉框的面板放入内容面板中
        this.getContentPane().add(textareascrollPane, "Center"); // 完成下拉框面板在内容面板中的边界布局,居中
        // 设置下拉框面板的下拉条总是可见
        textareascrollPane.setVerticalScrollBarPolicy(textareascrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    }


    /*
     * 单击事件处理
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取文本区的字体
        Font font = textArea.getFont();
        int fontStyle = font.getStyle();
        int fontSize = font.getSize();
        String fontName = font.getName();
        // 判断是否点击了“文件”菜单
        if (e.getSource() instanceof JMenuItem) {
            // 处理打开文件事件
            if (e.getActionCommand() == "打开") {
                // System.out.println("open !"); //该语句用于设计师的测试
                Openfile();
            }
             // 处理保存文件事件
            if (e.getActionCommand() == "保存") {
                // System.out.println("save !"); //该语句用于设计师的测试
                Savefile();
            }
            // 点击退出就退出程序
            if (e.getActionCommand() == "退出") {
                // System.out.println("exit !"); //该语句用于设计师的测试
                Exiteditor();
            }
        }
        // 判断是否点击了“编辑”菜单
        if (e.getSource() instanceof JMenuItem) {
            // 处理复制事件
            if (e.getActionCommand() == "复制") {
                String tempText = textArea.getSelectedText(); // 拖动鼠标选取文本
                // 创建能传输指定 String 的 Transferable。
                StringSelection editText = new StringSelection(tempText);
                /*
                 * 将剪贴板的当前内容设置到指定的 transferable 对象, 并将指定的剪贴板所有者作为新内容的所有者注册。
                 */
                clipboard.setContents(editText, null);
                return;
            }
            // 处理粘贴事件
            if (e.getActionCommand() == "粘贴") {
                // textArea.paste();
                // System.out.println("1234"); 测试数据
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();
                Transferable contents = clipboard.getContents(this);
                DataFlavor flavor = DataFlavor.stringFlavor;
                if (contents.isDataFlavorSupported(flavor)) {
                    try {
                        String str;
                        str = (String) contents.getTransferData(flavor);
                        // System.out.println(str); 测试数据
                        textArea.replaceRange(str, start, end);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                // setSysClipboardText("");
                return;
            }
            // 处理删除事件
            if (e.getActionCommand() == "删除") {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();
                textArea.replaceRange("", start, end);
                return;
            }
            // 处理剪切事件
            if (e.getActionCommand() == "剪切") {
                String tempText = textArea.getSelectedText();
                StringSelection editText = new StringSelection(tempText);
                clipboard.setContents(editText, null);
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();
                textArea.replaceRange("", start, end); // 从Text1中删除被选取的文本。
                return;
            }
        }
        //对字体风格和文字大小的处理
        if (e.getSource() instanceof JComboBox) {
             //处理文字大小
            if (e.getSource().equals(comboBoxOfFontsize)) {
                 // 获取字体大小组合选中字体大小
                // fontSize = (int) comboBoxOfFontsize.getSelectedItem();
                String fontSize2;
                fontSize2 = (String) comboBoxOfFontsize.getSelectedItem();
                // 修改文本区字体
                textArea.setFont(new Font(fontName, fontStyle, Integer.parseInt(fontSize2)));
            }
            //处理字体风格
            if (e.getSource().equals(comboBoxOfFontName)) {
                // 获取字体组合选中字体名
                fontName = (String) comboBoxOfFontName.getSelectedItem();
                // 修改文本区字体
                textArea.setFont(new Font(fontName, fontStyle, fontSize));
            }
        }
        //对文字进行加粗或者还原处理
        if (e.getSource().equals(checkBoxOfFontStylebold)) {
            fontStyle = fontStyle ^ 1; // ^ 异或运算 (加粗:和1做异或运算)
            textArea.setFont(new Font(fontName, fontStyle, fontSize));
        }
        //对文字进行倾斜或者还原处理
        if (e.getSource().equals(checkBoxOfFontStyleitalic)) {
            fontStyle = fontStyle ^ 2; // (斜体:和2做异或运算)
            textArea.setFont(new Font(fontName, fontStyle, fontSize));
        }
        /*
         * 对文字进行变色处理
         */
        if (e.getSource().equals(radiobuttonred)) {
            textArea.setForeground(Color.red);
        }


        if (e.getSource().equals(radiobuttonblue)) {
            textArea.setForeground(Color.blue);
        }


        if (e.getSource().equals(radiobuttongreen)) {
            textArea.setForeground(Color.green);
        }
    }
    /**
     *对系统的剪辑板进行覆盖的方法
     */
    public static void setSysClipboardText(String writeMe) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe); // 覆盖系统剪切板
        clip.setContents(tText, null);
    }
    /**
     * 打开文件方法封装
     */
    public void Openfile() {
        JFileChooser fileChooser = new JFileChooser("d:\\");
        // fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        // 这句用于硬性规定只能选择文件夹,而不能选择文件
        int returnVal = fileChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) { // 如果选择了对话框中的确定按钮,就执行以下操作
            File openfilePath = fileChooser.getSelectedFile();// 这个就是你选择的文件夹的路径
            try { // 流操作
                FileInputStream input = new FileInputStream(openfilePath); // FileInputStream文件输入流,将文件数据读出来
                BufferedReader breader = new BufferedReader(new InputStreamReader(input)); // BufferedReader字符输入流提高读出速率
                String tempreader = "";
                while ((tempreader = breader.readLine()) != null) { // 将读出的数据一行一行地写入程序(文本编辑器)的文本域中
                    textArea.append(tempreader);
                }
                breader.close(); // 关闭字符输入流
                input.close(); // 关闭文件输入流
            } catch (FileNotFoundException e1) { // 异常处理
                e1.printStackTrace(); // printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。
            } catch (IOException e1) {
                e1.printStackTrace(); // printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。
            }
        } else {
            // 由于系统自己有取消的方法所以这里就不扩充了!
        }
    }
    /**
     * 保存文件方法封装
     */
    public void Savefile() {
        File savefilePath = new File("D:/javaeditortest/editor.txt"); // 保存文件的路径
        try {
            FileOutputStream output = new FileOutputStream(savefilePath); // FileOutputStream文件输出流,将数据写入文件
            BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(output)); // BufferedWriter字符输出流提高写入速率
            for (String textareatemp : textArea.getText().split("\n")) { // 遍历,此处的textArea.getText().split("\n")可以当做一个数组,让后遍历处理,加上换行处理
                bwriter.write(textareatemp); // 将文本域的内容写入文件中
                bwriter.newLine();// 换行
            }
            bwriter.flush(); // 刷新字符输出流通道
            bwriter.close(); // 关闭字符输出流
            output.close(); // 关闭文件输出流
            JOptionPane.showMessageDialog(null, "已经保存成功啦!");
        } catch (FileNotFoundException e) {
            e.printStackTrace(); // printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。
        } catch (IOException e) {
            e.printStackTrace(); // printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。
        }
    }
    /**
     * 退出文本编辑器的方法封装
     */
    public void Exiteditor() {
        if (JOptionPane.showConfirmDialog(this, "退出系统?") == 0) {
            System.exit(0);
        }
    }
    public static void main(String[] args) {
        Editor02 editor = new Editor02();
        editor.setVisible(true);
    }
}

  • 16
    点赞
  • 105
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,这是一个简单的Java记事本实现示例: ```java import java.io.*; import java.util.Scanner; public class SimpleNotepad { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to Simple Notepad!"); while (true) { System.out.println("Enter '1' to create a new file, '2' to open an existing file, or '3' to exit:"); int choice = scanner.nextInt(); switch (choice) { case 1: createFile(); break; case 2: openFile(); break; case 3: System.out.println("Exiting Simple Notepad..."); System.exit(0); break; default: System.out.println("Invalid choice. Please try again."); } } } private static void createFile() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the name of the file to create:"); String filename = scanner.nextLine(); try { File file = new File(filename); if (file.createNewFile()) { System.out.println("File created: " + file.getAbsolutePath()); } else { System.out.println("File already exists."); } FileWriter writer = new FileWriter(file); System.out.println("Enter text to write to the file:"); String text = scanner.nextLine(); writer.write(text); writer.close(); System.out.println("Text written to file."); } catch (IOException e) { System.out.println("Error creating file: " + e.getMessage()); } } private static void openFile() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the name of the file to open:"); String filename = scanner.nextLine(); try { File file = new File(filename); if (file.exists()) { FileReader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String line; System.out.println("File contents:"); while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } reader.close(); } else { System.out.println("File does not exist."); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } } ``` 这个简单的记事本程序提供了三个选项:创建新文件、打开现有文件或退出程序。如果选择创建新文件,程序会要求用户输入文件名和要写入文件的文本。如果选择打开现有文件,程序会要求用户输入文件名并显示文件内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值