JavaSE 基于AWT的记事本实现

{功能描述}
NoteBook 类是一个记事本的基本类,该类的对象具有记事本的基本功能,包括:
打开文件、保存文件以及文本的复制、粘贴、删除等。
该程序主要包括为窗口添加菜单栏、在菜单栏中添加菜单以及为菜单栏添加菜单项,并且为每一个菜单项添加相应的监听器完成相应的操作。另外,还包括文件内容的读取和保存。

{相关代码}

package sup.orange.learn;

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.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by re-x on 11/3/14.
 */
public class NoteBook extends Frame implements ActionListener{
    MenuBar menuBar = new MenuBar();

    TextArea textArea = new TextArea();

    // file menu
    Menu fileMenu = new Menu("File");
    MenuItem newItem = new MenuItem("New");
    MenuItem openItem = new MenuItem("Open");
    MenuItem saveItem = new MenuItem("Save");
    MenuItem saveAsItem = new MenuItem("Save As");
    MenuItem exitItem = new MenuItem("Exit");

    // edit menu
    Menu editMenu = new Menu("Edit");
    MenuItem selectItem = new MenuItem("Select All");
    MenuItem copyItem = new MenuItem("Copy");
    MenuItem cutItem = new MenuItem("Cut");
    MenuItem pasteItem = new MenuItem("Paste");

    String fileName = "NoName.txt";
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Clipboard clipboard = toolkit.getSystemClipboard();


    // create and init open file dialog && save file dialog
    private FileDialog openFileDialog = new FileDialog(this, "Open File", FileDialog.LOAD);
    private FileDialog saveAsFileDialog = new FileDialog(this, "Save As", FileDialog.SAVE);

    public NoteBook() {
        setTitle("NotePad");
        setFont(new Font("Times New Roman", Font.PLAIN, 12));
        setBackground(Color.gray);
        setSize(600, 400);

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.addSeparator();
        fileMenu.add(saveItem);
        fileMenu.add(saveAsItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);

        editMenu.add(selectItem);
        editMenu.addSeparator();
        editMenu.add(copyItem);
        editMenu.add(cutItem);
        editMenu.add(pasteItem);

        menuBar.add(fileMenu);
        menuBar.add(editMenu);

        setMenuBar(menuBar);
        add(textArea);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                dispose();
                System.exit(0);
            }
        });

        newItem.addActionListener(this);
        openItem.addActionListener(this);
        saveItem.addActionListener(this);
        saveAsItem.addActionListener(this);
        exitItem.addActionListener(this);

        selectItem.addActionListener(this);
        copyItem.addActionListener(this);
        cutItem.addActionListener(this);
        pasteItem.addActionListener(this);

    }

    public static void main(String[] args) {
        Frame frame = new NoteBook();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // get screen size
        Dimension frameSize = frame.getSize();  // get frame size

        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }

        frame.setLocation((screenSize.width-frameSize.width)/2, (screenSize.height-frameSize.height)/2);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        Object eventSource = e.getSource();

        // judge which menuItem is the source
        if (eventSource == newItem) {
            textArea.setText("");
        }
        else if (eventSource == openItem) {
            openFileDialog.setVisible(true);
            fileName = openFileDialog.getDirectory()+openFileDialog.getFile();
            if (fileName != null) {
                readFile(fileName);
            }
        }
        else if (eventSource == saveItem) {
            if (fileName != null) {
                writeFile(fileName);
            }
        }
        else if (eventSource == saveAsItem) {
            saveAsFileDialog.setVisible(true);
            fileName = saveAsFileDialog.getDirectory()+saveAsFileDialog.getFile();
            if (fileName != null) {
                writeFile(fileName);
            }
        }
        else if (eventSource == selectItem) {
            textArea.selectAll();
        }
        else if (eventSource == copyItem) {
            String text = textArea.getSelectedText();
            StringSelection selection = new StringSelection(text);
            clipboard.setContents(selection, null);
        }
        else if (eventSource == cutItem) {
            String text = textArea.getSelectedText();
            StringSelection selection = new StringSelection(text);
            clipboard.setContents(selection, null);
            textArea.replaceRange("", textArea.getSelectionStart(), textArea.getSelectionEnd());
        }
        else if (eventSource == pasteItem) {
            Transferable contents = clipboard.getContents(this);
            if (contents == null) {
                return;
            }
            String text = "";
            try {
                text = (String)contents.getTransferData(DataFlavor.stringFlavor);
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }

            textArea.replaceRange(text, textArea.getSelectionStart(), textArea.getSelectionEnd());
        }
        else if (eventSource == exitItem) {
            System.exit(0);
        }
    }

    public void readFile(String fileName) {
        try {
            File file = new File(fileName);
            FileReader readIn = new FileReader(file);
            int size = (int)file.length();
            int charsRead = 0;
            char [] content = new char[size];

            while (readIn.ready()) {
                charsRead += readIn.read(content, charsRead, size-charsRead);
            }
            readIn.close();
            textArea.setText(new String(content, 0, charsRead));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeFile(String fileName) {
        try {
            File file = new File(fileName);
            FileWriter writeOut = new FileWriter(file);
            writeOut.write(textArea.getText());
            writeOut.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/aqing1987/p/4292599.html