Java版记事本。

利用Java编写的记事本软件。

今天整理电脑资料的时候,发现了几个大学时候做的程序,感觉挺有趣的,实现类似于Windows记事本的程序。

整体以Java swing技术为图形界面,然后配合Java的I/O技术作为文件管理。

package notepad;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.*;

public class Notepad implements ActionListener {

    /**
     * 窗体操作
     */

    // 声明组件
    private JFrame jframe = new JFrame();// jframe界面
    private JMenuBar menuBar;// 菜单条
    private JMenu file, edit, type, more;// bar上的第1,2,3,4个按钮
    private JMenuItem newFile, openFile, savaFile, newSave, exit;// file里面的选项
    private JMenuItem about, help;// more上的选项
    private JTextArea txt;// 文本域
    private JScrollPane jsp;// 滚文本域动条
    private JCheckBox jradioButton;// type里面的自动换行选项
    private JMenu font;// type里面的字体项
    private JMenu fontsize, fontcolor;// 字体大小,颜色
    private JRadioButton fontsize1, fontsize2, fontsize3;// 字号
    private JRadioButton fontcolor1, fontcolor2, fontcolor3;// 颜色
    private ButtonGroup bg1, bg2;// 单选组
    private JMenuItem copy, cut, Paste, del;// 复制,剪切,粘贴,删除(编辑块里面的)
    private JMenuItem copy1, cut1, Paste1, del1;// 复制,剪切,粘贴,删除(弹出式菜单里面的)
    private JPopupMenu jpopu;// 弹出式菜单条

    /**
     * 实例化各类组件
     */
    public Notepad() {

        menuBar = new JMenuBar();// menuBar
        menuBar.setBackground(new Color(230, 230, 250));

        jpopu = new JPopupMenu();// jpopu
        jpopu.setPopupSize(60, 80);
        jpopu.setVisible(false);

        file = new JMenu("文件(F)");// 实例化file按钮
        file.setFont(new Font("Monospaced", Font.PLAIN, 13));
        file.setBackground(new Color(230, 230, 250));
        file.addActionListener(this);
        file.setMnemonic(java.awt.event.KeyEvent.VK_F);

        edit = new JMenu("编辑(E)");// 实例化edit块
        edit.setFont(new Font("Monospaced", Font.PLAIN, 13));
        edit.setBackground(new Color(230, 230, 250));
        edit.addActionListener(this);
        edit.setMnemonic(java.awt.event.KeyEvent.VK_E);

        type = new JMenu("格式(T)");// 实例化type块
        type.setFont(new Font("Monospaced", Font.PLAIN, 13));
        type.setBackground(new Color(230, 230, 250));
        type.addActionListener(this);
        type.setMnemonic(java.awt.event.KeyEvent.VK_T);

        more = new JMenu("更多(M)");// 实例化more块
        more.setFont(new Font("Monospaced", Font.PLAIN, 13));
        more.setBackground(new Color(230, 230, 250));
        more.addActionListener(this);
        more.setMnemonic(java.awt.event.KeyEvent.VK_M);

        newFile = new JMenuItem("新建(N)");// file块中的
        newFile.setBackground(new Color(230, 230, 250));
        newFile.addActionListener(this);
        newFile.setMnemonic(java.awt.event.KeyEvent.VK_N);

        openFile = new JMenuItem("打开(O)");// file块中的
        openFile.setBackground(new Color(230, 230, 250));
        openFile.addActionListener(this);
        openFile.setMnemonic(java.awt.event.KeyEvent.VK_O);

        savaFile = new JMenuItem("保存(S)");// file块中的
        savaFile.setBackground(new Color(230, 230, 250));
        savaFile.addActionListener(this);
        savaFile.setMnemonic(java.awt.event.KeyEvent.VK_S);

        newSave = new JMenuItem("另存为");// file块中的
        newSave.setBackground(new Color(230, 230, 250));
        newSave.addActionListener(this);

        exit = new JMenuItem("退出(X)");// file块中的
        exit.setBackground(new Color(230, 230, 250));
        exit.addActionListener(this);
        exit.setMnemonic(java.awt.event.KeyEvent.VK_X);

        copy = new JMenuItem("复制(C)");// edit块中的
        copy.setBackground(new Color(230, 230, 250));
        copy.addActionListener(this);
        copy.setMnemonic(java.awt.event.KeyEvent.VK_C);

        cut = new JMenuItem("剪切(X)");// edit块中的
        cut.setBackground(new Color(230, 230, 250));
        cut.addActionListener(this);
        cut.setMnemonic(java.awt.event.KeyEvent.VK_X);

        Paste = new JMenuItem("粘贴(V)");// edit块中的
        Paste.setBackground(new Color(230, 230, 250));
        Paste.addActionListener(this);
        Paste.setMnemonic(java.awt.event.KeyEvent.VK_V);

        del = new JMenuItem("删除(D)");// edit块中的
        del.setBackground(new Color(230, 230, 250));
        del.addActionListener(this);
        del.setMnemonic(java.awt.event.KeyEvent.VK_D);

        copy1 = new JMenuItem("复制(C)");// jpopu块中的
        copy1.setBackground(new Color(230, 230, 250));
        copy1.addActionListener(this);
        copy1.setMnemonic(java.awt.event.KeyEvent.VK_C);

        cut1 = new JMenuItem("剪切(X)");// jpopu块中的
        cut1.setBackground(new Color(230, 230, 250));
        cut1.addActionListener(this);
        cut1.setMnemonic(java.awt.event.KeyEvent.VK_X);

        Paste1 = new JMenuItem("粘贴(V)");// jpopu块中的
        Paste1.setBackground(new Color(230, 230, 250));
        Paste1.addActionListener(this);
        Paste1.setMnemonic(java.awt.event.KeyEvent.VK_V);

        del1 = new JMenuItem("删除(D)");// jpopu块中的
        del1.setBackground(new Color(230, 230, 250));
        del1.addActionListener(this);
        del1.setMnemonic(java.awt.event.KeyEvent.VK_D);

        jradioButton = new JCheckBox("自动换行");// type块中的
        jradioButton.addActionListener(this);
        jradioButton.setSelected(true);

        about = new JMenuItem("关于(A)");// more块里面的
        about.setBackground(new Color(230, 230, 250));
        about.addActionListener(this);

        help = new JMenuItem("帮助(H)");// more块里面的
        help.setBackground(new Color(230, 230, 250));
        help.addActionListener(this);

        /*
         * 把需要添加到jpopu块中的内容进行添加
         *
         */
        jpopu.add(copy1);
        jpopu.addSeparator();// 分割线
        jpopu.add(cut1);
        jpopu.addSeparator();// 分割线
        jpopu.add(Paste1);
        jpopu.addSeparator();// 分割线
        jpopu.add(del1);

        /*
         * 实例化文本域
         */
        txt = new JTextArea();// 此处不设置大小,23, 109---因为是直接添加到jframe里面的
        txt.setBackground(Color.white);
        txt.setFont(new Font("Monospaced", Font.PLAIN, 19));
        txt.setForeground(Color.black);
        txt.setLineWrap(true);
        /*
         * 对文本域txt的方块进行鼠标事件监听>>>>>> 产生右键事件, 显示弹出式菜单jopopu块中的内容
         *
         */
        txt.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
                    jpopu.show(txt, e.getX(), e.getY());

                }
            }
        });

        /*
         * 对文本域txt的方块进行键盘事件监听>>>>>> 产生键盘事件, 发生相应对文本的的处理方式。
         *
         *
         */
        txt.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if ((e.getKeyCode() == KeyEvent.VK_S) && (e.isControlDown())) {// ctrl+s
                    sava();
                } // 与windows的键值重复
                if ((e.getKeyCode() == KeyEvent.VK_O) && (e.isControlDown())) {// ctrl+o
                    openFile();
                }
                // if ((e.getKeyCode() == KeyEvent.VK_N) && (e.isControlDown()))
                // {// ctrl+n
                // newFile();
                // }
                // if ((e.getKeyCode() == KeyEvent.VK_C) && (e.isControlDown()))
                // {// ctrl+c
                // copy();
                // }
                // if ((e.getKeyCode() == KeyEvent.VK_X) && (e.isControlDown()))
                // {// ctrl+x
                // cut();
                // } // 这里使用的话会和windows的复制共用,是的复制两次内容
                // if ((e.getKeyCode() == KeyEvent.VK_V) &&
                // (e.isControlDown()))
                // {// ctrl+v
                // Paste();
                // }
                if ((e.getKeyCode() == KeyEvent.VK_D) && (e.isControlDown())) {// ctrl+d
                    del();
                }
            }
        });

        font = new JMenu("字体选项");
        font.setBackground(new Color(230, 230, 250));

        fontsize = new JMenu("字体大小");
        fontsize.setBackground(new Color(230, 230, 250));

        fontcolor = new JMenu("字体颜色");
        fontcolor.setBackground(new Color(230, 230, 250));

        bg1 = new ButtonGroup();
        bg2 = new ButtonGroup();

        fontsize1 = new JRadioButton("小号");
        fontsize1.setBackground(new Color(230, 230, 250));
        fontsize1.addActionListener(this);

        fontsize2 = new JRadioButton("中号");
        fontsize2.setBackground(new Color(230, 230, 250));
        fontsize2.addActionListener(this);

        fontsize3 = new JRadioButton("大号");
        fontsize3.setBackground(new Color(230, 230, 250));
        fontsize3.addActionListener(this);

        bg1.add(fontsize1);
        bg1.add(fontsize2);
        bg1.add(fontsize3);

        fontsize.add(fontsize1);
        fontsize.add(fontsize2);
        fontsize.add(fontsize3);

        fontcolor1 = new JRadioButton("红色");
        fontcolor1.setBackground(new Color(230, 230, 250));
        fontcolor1.addActionListener(this);

        fontcolor2 = new JRadioButton("绿色");
        fontcolor2.setBackground(new Color(230, 230, 250));
        fontcolor2.addActionListener(this);

        fontcolor3 = new JRadioButton("蓝色");
        fontcolor3.setBackground(new Color(230, 230, 250));
        fontcolor3.addActionListener(this);

        bg2.add(fontcolor1);
        bg2.add(fontcolor2);
        bg2.add(fontcolor3);

        fontcolor.add(fontcolor1);
        fontcolor.add(fontcolor2);
        fontcolor.add(fontcolor3);
    }

    /**
     * 添加各类组件到相应的容器。
     */
    public void add() {

        jframe.setTitle("记事本");// 程序的名字
        jframe.setSize(600, 430);// 程序界面的大小
        jframe.setResizable(true);// 更改程序界面的大小
        // jframe.getContentPane().add(main);// 把主面板main添加到获取的容器里面。
        jframe.setLocationRelativeTo(null);// 居中启动应用
        jframe.setJMenuBar(menuBar);// 设定jframe的菜单条

        jsp = new JScrollPane(txt);// 实例化滚动条(传一个文本域进去),并添加txt文本域到main中
        jframe.getContentPane().add(jsp);

        file.add(newFile);// 把file块中放的内容添加进去。
        file.add(openFile);
        file.add(savaFile);
        file.add(newSave);
        file.addSeparator();// 添加了一条横的分割线
        file.add(exit);

        edit.add(copy);// 把edit块中放的内容添加进去
        edit.addSeparator();// 添加了一条分割线
        edit.add(cut);
        edit.addSeparator();
        edit.add(Paste);
        edit.addSeparator();
        edit.add(del);

        type.add(jradioButton);// 把type块中的放的内容添加进去

        more.add(about);// 把more块中放的内容添加进去
        more.add(help);

        menuBar.add(file);// 添加bar上的操作块
        menuBar.add(edit);
        menuBar.add(type);
        menuBar.add(more);

        font.add(fontsize);
        font.add(fontcolor);
        type.add(font);

        jframe.setVisible(true);// 设置窗体可见
        jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jframe.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                exit();
            }
        });
    }

    /*
     * copy的操作
     */
    private static StringSelection stsel = null;

    private Clipboard clipboard = jframe.getToolkit().getSystemClipboard();

    public void copy() {
        String tempText = txt.getSelectedText(); // 拖动鼠标选取文本
        stsel = new StringSelection(tempText);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
    }

    /*
     * cut的操作
     */
    public void cut() {
        String tempText = txt.getSelectedText();
        StringSelection editText = new StringSelection(tempText);
        clipboard.setContents(editText, null);
        int start = txt.getSelectionStart();
        int end = txt.getSelectionEnd();
        txt.replaceRange("", start, end);
    }

    /*
     * Paste的操作
     */
    public void Paste() {
        Transferable contents = clipboard.getContents(this);
        DataFlavor flavor = DataFlavor.stringFlavor;
        if (contents.isDataFlavorSupported(flavor)) {
            try {
                String str;
                str = (String) contents.getTransferData(flavor);
                txt.setText(txt.getText() + str);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /*
     * del的操作
     */
    public void del() {
        int start = txt.getSelectionStart();
        int end = txt.getSelectionEnd();
        txt.replaceRange("", start, end);
    }

    /*
     * i/o操作
     */

    private static File OpenFile = null;// 打开文件对象
    private static File SavaFile = null;// 保存文件对象
    private static BufferedReader br = null;// 缓冲流-----读
    private static BufferedWriter bw = null;// 缓冲流-----写

    /*
     * 新建文件的操作
     */
    public void newFile() {
        new Notepad().add();
    }

    /*
     * 打开文件的操作
     */
    public void openFile() {
        int result;
        StringBuilder str = new StringBuilder();
        String temp;
        JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        result = fileChooser.showOpenDialog(null);

        if (JFileChooser.APPROVE_OPTION == result) {
            OpenFile = new File(fileChooser.getSelectedFile().getPath());
            try {
                br = new BufferedReader(new FileReader(OpenFile));
                while ((temp = br.readLine()) != null) {
                    str.append(temp).append("\r\n");
                }
                br.close();
                txt.setText(str.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 保存文件的操作
     */
    public void sava() {
        int result = 0;
        String temp = txt.getText();
        JFileChooser fileChooser = new JFileChooser();
        result = fileChooser.showSaveDialog(null);
        if (JFileChooser.APPROVE_OPTION == result) {
            SavaFile = new File(fileChooser.getSelectedFile().getPath());
            boolean isWrite = true;
            if (SavaFile.exists()) {
                int confirmValue = JOptionPane.showConfirmDialog(null, SavaFile + "文件已经存在,是否覆盖?", "保存", JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE);
                if (confirmValue != JOptionPane.YES_OPTION) {
                    isWrite = false;
                }
            }
            if (isWrite)
                try {
                    bw = new BufferedWriter(new FileWriter(SavaFile));
                    bw.write(temp);
                    bw.flush();
                    bw.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            if (isCloseIng) {
                this.jframe.dispose();
            }
        }

    }

    /*
     * 退出的操作
     */
    public void exit() {
        String temp = txt.getText();
        if (temp != null && temp.length() > 0) {
            int confirmValue = JOptionPane.showConfirmDialog(null, "是否保存内容?", "保存", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (confirmValue == JOptionPane.YES_OPTION) {
                isCloseIng = true;
                sava();
            } else {
                this.jframe.dispose();
            }
        } else {
            this.jframe.dispose();
        }
    }

    /*
     *是否是退出操作中的保存
     */
    private static boolean isCloseIng = false;

    /*
     * 关于块的操作
     */
    public String about() {
        return "这是纯java编写的记事本软件";
    }

    /*
     * help块的操作
     */
    public String help() {
        return "如果在使用过程中遇到问题,请联系作者!";
    }

    /*
     * 对监听了得组件进行实现方法
     *
     *
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == newFile) {// 新建文件
            newFile();
        }
        if (e.getSource() == openFile) {// 打开文件
            openFile();
        }
        if (e.getSource() == savaFile) {// 保存文件
            sava();
        }
        if (e.getSource() == newSave) {// 另存为文件
            sava();
        }
        if (e.getSource() == exit) {// 退出操作
            exit();
        }
        if (e.getSource() == about) {// 关于操作
            JOptionPane.showMessageDialog(null, about());
        }
        if (e.getSource() == help) {// 帮助操作
            JOptionPane.showMessageDialog(null, help());
        }
        if (e.getSource() == jradioButton && jradioButton.isSelected()) {// 换行操作
            txt.setLineWrap(true);
        } else if (e.getSource() == jradioButton && !jradioButton.isSelected()) {
            txt.setLineWrap(false);
        }
        /*
         * edit、弹出式菜单 的操作
         */
        if (e.getSource() == copy || e.getSource() == copy1) {// 复制
            copy();
        }
        if (e.getSource() == cut || e.getSource() == cut1) {// 剪切
            cut();
        }
        if (e.getSource() == Paste || e.getSource() == Paste1) {// 粘贴
            Paste();
        }
        if (e.getSource() == del || e.getSource() == del1) {// 删除
            del();
        }

        /*
         * 字体大小操作
         */
        if (e.getSource() == fontsize1 && fontsize1.isSelected()) {
            txt.setFont(new Font("Monospaced", Font.PLAIN, 13));
        }
        if (e.getSource() == fontsize2 && fontsize2.isSelected()) {
            txt.setFont(new Font("Monospaced", Font.PLAIN, 22));
        }
        if (e.getSource() == fontsize3 && fontsize3.isSelected()) {
            txt.setFont(new Font("Monospaced", Font.PLAIN, 30));
        }
        /*
         * 字体颜色操作
         */
        if (e.getSource() == fontcolor1 && fontcolor1.isSelected()) {
            txt.setForeground(Color.red);
        }
        if (e.getSource() == fontcolor2 && fontcolor2.isSelected()) {
            txt.setForeground(Color.green);
        }
        if (e.getSource() == fontcolor3 && fontcolor3.isSelected()) {
            txt.setForeground(Color.blue);
        }
    }

    /*
     * 程序入口
     */
    public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
        /*
         * 设置Windows风格
         */
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        new Notepad().add();
    }

}

软件运行截图:

主界面

软件运行截图

猜你喜欢

转载自blog.csdn.net/qq_37157160/article/details/84899943