简单记事本的实现(JAVA)

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Notebook
{
    private ArrayList <String> notes;
    private File file;

    public Notebook()
    {
        notes = new ArrayList <String>();
        file = new File("note.txt");

        Scanner fReader;
        try {
            fReader = new Scanner(file);
            while (fReader.hasNext()) {
                notes.add(fReader.next());
            }
            fReader.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void storeNote(String note)
    {
        notes.add(note);
        try {
            PrintWriter pw = new PrintWriter(new FileWriter(file,true));
            pw.println(note);
            pw.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int numberOfNotes()
    {
        return notes.size();
    }

    public String showNote(int noteNumber)
    {
        if (noteNumber < 0) {
            return null;
        }
        else if (noteNumber < numberOfNotes()) {
            //This is a valid note number, so we can print it.
            return notes.get(noteNumber);
        }
        else {
            return null;
        }
    }

    public void removeNote(int noteNumber)
    {
        if (noteNumber < 0) {
            //This is not a valid note number, so do nothing.
        }
        else if (noteNumber < numberOfNotes()) {
            //This is a valid note number.
            notes.remove(noteNumber);
        }
        else {
            //This is not a valid note number, so do nothing.
        }
    }

    public static void main(String[] args) {
        Notebook note1 = new Notebook();

        note1.storeNote("2013-09-25");
        note1.storeNote("2012-12-12");
        note1.storeNote("2012-09-10");

        System.out.println("当前记事本中有" + note1.numberOfNotes() + "条记录" );

        note1.showNote(2);
        note1.listNotes();
        note1.removeNote(0);
        note1.listNotes();
    }

    public String listNotes()//for-each循环
    {
        String notesString = "";
        for (String note : notes) {
            notesString = notesString + note + "\n";
        }
        return notesString;
    }

    /*public void listNotes()//while循环
    {
      int index = 0;
      while (index < notes.size()) {
        System.out.println(notes.get(index));
        index ++;
      }
    }

    public void listNotes()//迭代器循环
    {
      Iterator <String> it = notes.iterator();
      while (it.hasNext()) {
        System.out.println(it.next());
      }
    }*/
    public String search(String searchString)
    {
        String noteString = "";
        int index = 0;

        while (index < notes.size()) {
            String note = notes.get(index);
            if (note.contains(searchString)) {
                noteString = noteString + note + "\n";
            }
            index ++;
        }
        return noteString;
    }
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class NotebookFrame {
    private JFrame frame;
    private JTextField add_text;
    private JTextField find_text;
    private JTextArea view_text;
    private JButton add_button;
    private JButton find_button;
    private JButton delete_button;
    private JButton list_button;
    private JLabel state_Label;
    private JLabel add_Label;
    private JLabel find_Label;
    private JRadioButton rb1;
    private JRadioButton rb2;
    private Notebook notebook;

    public NotebookFrame() {
        notebook = new Notebook();
        makeFrame();
    }

    public void makeFrame() {
        frame = new JFrame("记事本");
        JPanel contentPane = (JPanel)frame.getContentPane();
        JPanel northPanel = new JPanel(new GridLayout(3,1));
        JPanel north1 = new JPanel(new FlowLayout());
        JPanel north2 = new JPanel(new FlowLayout());
        JPanel north3 = new JPanel(new GridLayout());

        northPanel.add(north1);
        northPanel.add(north2);
        northPanel.add(north3);

        JPanel southPanel = new JPanel(new GridLayout(0,1));
        JPanel south1 = new JPanel(new GridLayout(1,2,5,5));
        JPanel south2 = new JPanel(new FlowLayout());
        southPanel.add(south1);
        southPanel.add(south2);
        contentPane.add(northPanel,BorderLayout.NORTH);
        contentPane.add(southPanel,BorderLayout.SOUTH);

        add_text = new JTextField(16);
        find_text = new JTextField(16);
        view_text = new JTextArea(12,16);
        JScrollPane scrollbar = new JScrollPane(view_text);
        add_button = new JButton("添加");
        String newNote = add_text.getText();
        notebook.storeNote(newNote);
        state_Label = new JLabel();
        state_Label.setText("当前记事本中有" + notebook.numberOfNotes() + "条记录");
        add_text.setText(null);
        find_button = new JButton("查询");
        find_button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent args0) {
                if (rb2.isSelected()) {
                    int noteNum = Integer.parseInt(find_text.getText());
                    String note = notebook.showNote(noteNum);
                    view_text.setText(note);
                }
                else if (rb1.isSelected()) {
                    String note = notebook.search(find_text.getText().trim());
                    view_text.setText(note);
                }
            }
        });
        delete_button = new JButton("删除记录");
        list_button = new JButton("列表显示");

        list_button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent args0) {
                view_text.setText(notebook.listNotes());
            }
        });
        state_Label = new JLabel("当前记事本中有" + notebook.numberOfNotes() + "条记录");
        add_Label = new JLabel("输入新记录:");
        find_Label = new JLabel("输入关键字:");

        ButtonGroup buttonGroup = new ButtonGroup();
        rb1 = new JRadioButton("按关键字",true);
        rb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                find_Label.setText("按关键字:");
            }
        });
        rb2 = new JRadioButton("按记录号");
        rb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                find_Label.setText("按记录号:");
            }
        });
        buttonGroup.add(rb1);
        buttonGroup.add(rb2);

        contentPane.add(scrollbar);
        north1.add(add_text);
        north1.add(add_button);
        north1.add(add_Label);
        north2.add(find_text);
        north2.add(find_button);
        north2.add(find_Label);
        north3.add(rb1);
        north3.add(rb2);
        south1.add(delete_button);
        south1.add(list_button);
        south2.add(state_Label);

        frame.pack();

        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new NotebookFrame();
    }
}
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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值