基于JAVA的记事本实现,你们学会了吗?

本文详细描述了如何使用Java编程语言创建一个简单的文本编辑器,包括菜单栏的构建、文件操作(新建、打开、保存)、字体样式和颜色设置等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现一款属于自己的记事本:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;


public class Notepad {
    /*(1)使用顶层容器JFrame
    (2)设置功能菜单并通过BorderLayout进行边框布局管理。
    (3)设置相应按钮与文件编辑区。
    (4)进行相应事件处理。*/

    private JTextArea contentArea;

    private JFrame frame;

    private String fileName;

    public Notepad() {
        frame = new JFrame("记事本");
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 添加菜單
        JMenuBar menuBar = new JMenuBar();

        JMenu menu = new JMenu("文件");
        JMenuItem newItem = new JMenuItem("新建");
        newAction(newItem);

        menu.add(newItem);
        JMenuItem openItem = new JMenuItem("打开");
        openAction(openItem);
        menu.add(openItem);
        JMenuItem saveItem = new JMenuItem("保存");
        saveAction(saveItem);
        menu.add(saveItem);
        menuBar.add(menu);

        frame.setJMenuBar(menuBar);

        // 布局
        frame.setLayout(new BorderLayout());

        JToolBar toolBar = new JToolBar();
        JComboBox<String> fontCom = fontAction();
        toolBar.add(fontCom);
        JComboBox<String> fontSize = fontSizeAction();
        toolBar.add(fontSize);

        fontStyleAction(toolBar);
        JButton colorbtn = fontColorAction();
        toolBar.add(colorbtn);

        frame.add(toolBar, BorderLayout.NORTH);
        // 文件编辑区
        contentArea = new JTextArea();
        JScrollPane pane = new JScrollPane(contentArea);
        frame.add(pane);
        frame.setVisible(true);

    }

    private JButton fontColorAction() {
        JButton colorbtn = new JButton("■");
        colorbtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Color color = colorbtn.getForeground();
                Color co = JColorChooser.showDialog(Notepad.this.frame, "设置字体颜色", color);
                colorbtn.setForeground(co);
                contentArea.setForeground(co);
            }
        });
        return colorbtn;
    }

    // 记事本,字体格式
    private void fontStyleAction(JToolBar toolBar) {
        JCheckBox boldBox = new JCheckBox("粗体");
        JCheckBox itBox = new JCheckBox("斜体");
        ActionListener actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                boolean bold = boldBox.isSelected();
                boolean it = itBox.isSelected();
                int style = (bold ? Font.BOLD : Font.PLAIN) | (it ? Font.ITALIC : Font.PLAIN);
                Font font = contentArea.getFont();
                contentArea.setFont(new Font(font.getName(), style, font.getSize()));
                //contentArea.setFont(new Font(font.getName(), style, font.getSize()));
            }
        };
        boldBox.addActionListener(actionListener);
        itBox.addActionListener(actionListener);
        toolBar.add(boldBox);
        toolBar.add(itBox);
    }

    // 记事本,设置字体大小
    private JComboBox<String> fontSizeAction() {
        String[] fontSizes = new String[]{"10", "20", "30", "50"};
        JComboBox<String> fontSize = new JComboBox<>(fontSizes);
        fontSize.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int size = Integer.valueOf((String) fontSize.getSelectedItem());
                Font font = Notepad.this.contentArea.getFont();
                Notepad.this.contentArea.setFont(new Font(font.getName(), font.getStyle(), size));

            }
        });
        return fontSize;
    }

    // 记事本,设置字体
    private JComboBox<String> fontAction() {
        GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = environment.getAvailableFontFamilyNames();

        JComboBox<String> fontCom = new JComboBox<>(fontNames);

        fontCom.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String fontName = (String) fontCom.getSelectedItem();
                Font font = Notepad.this.contentArea.getFont();
                Notepad.this.contentArea.setFont(new Font(fontName, font.getStyle(), font.getSize()));

            }
        });
        return fontCom;
    }

    // 记事本新建操作
    private void newAction(JMenuItem newItem) {
        newItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                contentArea.setText("");
                frame.setTitle("新建-记事本");

                fileName = null;
            }
        });
    }

    // 记事本打开文件操作
    private void openAction(JMenuItem openItem) {
        openItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Text & dat", "txt", "dat");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    String fileName = chooser.getSelectedFile().getPath();
                    Notepad.this.fileName = fileName;
                    String content = read(fileName);
                    contentArea.setText(content);
                    Notepad.this.frame.setTitle(fileName + "- 记事本");
                }

            }
        });
    }

    // 菜单 保存操作
    private void saveAction(JMenuItem saveItem) {
        saveItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                if (Notepad.this.fileName != null) {
                    String content = Notepad.this.contentArea.getText();
                    write(Notepad.this.fileName, content);
                } else {
                    JFileChooser chooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text & dat", "txt", "dat");
                    chooser.setFileFilter(filter);
                    int returnVal = chooser.showSaveDialog(frame);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        String fileName = chooser.getSelectedFile().getPath();
                        Notepad.this.fileName = fileName;
                        String content = Notepad.this.contentArea.getText();
                        write(Notepad.this.fileName, content);
                        Notepad.this.frame.setTitle(fileName + "- 记事本");
                    }
                }
            }
        });
    }


    public String read(String fileName) {

        try (Reader reader = new FileReader(fileName); BufferedReader buff = new BufferedReader(reader);) {
            String str;
            StringBuilder sb = new StringBuilder();
            while ((str = buff.readLine()) != null) {
                str = decoding(str);
                sb.append(str + "\n");
            }

            return sb.toString();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "找不到文件路径" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void write(String fileName, String content) {

        try (Writer writer = new FileWriter(fileName);) {
            content = encoding(content);
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String encoding(String str) {
        String temp = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '\n') {
                temp += str.charAt(i);
            } else if (0 <= str.charAt(i) && str.charAt(i) <= 255) {
                temp += (char) ((str.charAt(i) - '0' + 10) % 255);
            } else {
                temp += str.charAt(i);
            }
        }
        return temp;
    }
    public String decoding(String str) {
        String temp = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '\n') {
                temp += str.charAt(i);
            } else if (0 <= str.charAt(i) && str.charAt(i) <= 255) {
                temp += (char) ((str.charAt(i) + '0' - 10 + 255) % 255);
            } else {
                temp += str.charAt(i);
            }
        }
        return temp;
    }
    public static void main(String[] args) {
 /*     (1)打开功能:
        用户点击打开后,可以选择文件中对应的txtdat文件,用户确定选择后即可打开改文件并展示文件中的内容,并在程序正上方展示当前文件路径。
        (2)新建功能:
        用户点击新建功能后,将展示一个空白的记事本,用户可进行相应编辑。
        (3)保存功能:
        用户点击保存后,如果保存的文件已经存在路径,则直接进行覆盖,若不存在,则需用户自己选择保存的路径,并对保存的文件进行命名。*/
        Notepad notepad = new Notepad();
    }
}

运行效果如下:

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; public class JNotePadUI extends JFrame { private JMenuItem menuOpen; private JMenuItem menuSave; private JMenuItem menuSaveAs; private JMenuItem menuClose; private JMenu editMenu; private JMenuItem menuCut; private JMenuItem menuCopy; private JMenuItem menuPaste; private JMenuItem menuAbout; private JTextArea textArea; private JLabel stateBar; private JFileChooser fileChooser; private JPopupMenu popUpMenu; public JNotePadUI() { super("新建文本文件"); setUpUIComponent(); setUpEventListener(); setVisible(true); } private void setUpUIComponent() { setSize(640, 480); // 菜单栏 JMenuBar menuBar = new JMenuBar(); // 设置「文件」菜单 JMenu fileMenu = new JMenu("文件"); menuOpen = new JMenuItem("打开"); // 快捷键设置 menuOpen.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_O, InputEvent.CTRL_MASK)); menuSave = new JMenuItem("保存"); menuSave.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_MASK)); menuSaveAs = new JMenuItem("另存为"); menuClose = new JMenuItem("关闭"); menuClose.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, InputEvent.CTRL_MASK)); fileMenu.add(menuOpen); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuSave); fileMenu.add(menuSaveAs); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuClose); // 设置「编辑」菜单 JMenu editMenu = new JMenu("编辑"); menuCut = new JMenuItem("剪切"); menuCut.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); menuCopy = new JMenuItem("复制"); menuCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menuPaste = new JMenuItem("粘贴"); menuPaste.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); editMenu.add(menuCut); editMenu.add(menuCopy); editMenu.add(menuPaste); // 设置「关于」菜单 JMenu aboutMenu = new JMenu("关于"); menuAbout = new JMenuItem("关于JNotePad"); aboutMenu.add(menuAbout); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); setJMenuBar(menuBar); // 文字编辑区域 textArea = new JTextArea(); textArea.setFont(new Font("宋体", Font.PLAIN, 16)); textArea.setLineWrap(true); JScrollPane panel = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); // 状态栏 stateBar = new JLabel("未修改"); stateBar.setHorizontalAlignment(SwingConstants.LEFT); stateBar.setBorder( BorderFactory.createEtchedBorder()); contentPane.add(stateBar, BorderLayout.SOUTH); popUpMenu = editMenu.getPopupMenu(); fileChooser = new JFileChooser(); } private void setUpEventListener() { // 按下窗口关闭钮事件处理 addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { closeFile(); } } ); // 菜单 - 打开 menuOpen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } } ); // 菜单 - 保存 menuSave.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFile(); } } ); // 菜单 - 另存为 menuSaveAs.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFileAs(); } } ); // 菜单 - 关闭文件 menuClose.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { closeFile(); } } ); // 菜单 - 剪切 menuCut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cut(); } } ); // 菜单 - 复制 menuCopy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { copy(); } } ); // 菜单 - 粘贴 menuPaste.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { paste(); } } ); // 菜单 - 关于 menuAbout.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示对话框 JOptionPane.showOptionDialog(null, "程序名称:\n JNotePad \n" + "程序设计:\n \n" + "简介:\n 一个简单的文字编辑器\n" + " 可作为验收Java实现对象\n" + " 欢迎网友下载研究交流\n\n" + " /", "关于JNotePad", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); } } ); // 编辑区键盘事件 textArea.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { processTextArea(); } } ); // 编辑区鼠标事件 textArea.addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) popUpMenu.show(editMenu, e.getX(), e.getY()); } public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) popUpMenu.setVisible(false); } } ); } private void openFile() { if(isCurrentFileSaved()) { // 文件是否为保存状态 open(); // 打开 } else { // 显示对话框 int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { // 确认文件保存 case JOptionPane.YES_OPTION: saveFile(); // 保存文件 break; // 放弃文件保存 case JOptionPane.NO_OPTION: open(); break; } } } private boolean isCurrentFileSaved() { if(stateBar.getText().equals("未修改")) { return false; } else { return true; } } private void open() { // fileChooser 是 JFileChooser 的实例 // 显示文件选取的对话框 int option = fileChooser.showDialog(null, null); // 使用者按下确认键 if(option == JFileChooser.APPROVE_OPTION) { try { // 开启选取的文件 BufferedReader buf = new BufferedReader( new FileReader( fileChooser.getSelectedFile())); // 设定文件标题 setTitle(fileChooser.getSelectedFile().toString()); // 清除前一次文件 textArea.setText(""); // 设定状态栏 stateBar.setText("未修改"); // 取得系统相依的换行字符 String lineSeparator = System.getProperty("line.separator"); // 读取文件并附加至文字编辑区 String text; while((text = buf.readLine()) != null) { textArea.append(text); textArea.append(lineSeparator); } buf.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "开启文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFile() { // 从标题栏取得文件名称 File file = new File(getTitle()); // 若指定的文件不存在 if(!file.exists()) { // 执行另存为 saveFileAs(); } else { try { // 开启指定的文件 BufferedWriter buf = new BufferedWriter( new FileWriter(file)); // 将文字编辑区的文字写入文件 buf.write(textArea.getText()); buf.close(); // 设定状态栏为未修改 stateBar.setText("未修改"); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "写入文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFileAs() { // 显示文件对话框 int option = fileChooser.showSaveDialog(null); // 如果确认选取文件 if(option == JFileChooser.APPROVE_OPTION) { // 取得选择的文件 File file = fileChooser.getSelectedFile(); // 在标题栏上设定文件名称 setTitle(file.toString()); try { // 建立文件 file.createNewFile(); // 进行文件保存 saveFile(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "无法建立新文件", JOptionPane.ERROR_MESSAGE); } } } private void closeFile() { // 是否已保存文件 if(isCurrentFileSaved()) { // 释放窗口资源,而后关闭程序 dispose(); } else { int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { case JOptionPane.YES_OPTION: saveFile(); break; case JOptionPane.NO_OPTION: dispose(); } } } private void cut() { textArea.cut(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void copy() { textArea.copy(); popUpMenu.setVisible(false); } private void paste() { textArea.paste(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void processTextArea() { stateBar.setText("已修改"); } public static void main(String[] args) { new JNotePadUI(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蜜蜂vs码农

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值