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

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

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

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

运行效果如下:

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小蜜蜂vs码农

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

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

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

打赏作者

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

抵扣说明:

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

余额充值