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);
    }
}

  • 20
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
所用工具:Jcreator 一.新建(ctrl+n)→判断:1.保存了,直接新建,框架名为:“新建 文本文档.txt--★海龙记事本★” 2.未保存:提示未保存,要求选则是否保存 选是,保存后新建;选否,不保存直接新建。 二.打开(strl+o)→判断:1.判断文件是否保存(同上) 然后打开,选择文件,只能选(.txt)文件 选择后在记事本中显示出来。 三.保存(ctrl+s)→判断:弹出保存对话框→输入文件名: 1. 如果没有填写后缀名→直接命名在名字后添加未.txt后缀 2. 如果填写了后缀名→则直接以保存为用户要求的后缀名。但是在关闭文件时还是提示未保存(原因是未保存为.txt文件) 四.另存为(F12)→判断:同上。 五.退出(Alt+F4)→判断:1.已保存,直接关闭。 3. 未保存→提示未保存,询问用户是否保存 选择→是:转到保存步骤 选择→否:直接关闭。 六.粘贴(ctrl+c)、复制(ctrl+v)、剪切(ctrl+x)、全选(ctrl+a)、 删除(delete)、时间/日期(F5): 点击或使用快捷键实现编写文件的编辑操作 功能全部实现 七、字体颜色(Ctrl+F): 点击或使用快捷键弹出字体颜色对话框 选择字体颜色后,文字颜色全部改变为所选颜色 八、字体(Ctrl+Q):点击或使用快捷弹出字体对话框 选择字体后,文字全部改变为所选字体 九、自动换行(Ctrl+Q):点击后实现自动换行 再点击后恢复 十、关于记事本(F1)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值