Javaswing实现记事本功能

效果图:

 首先,要对编写的程序进行分析,记事本由5大模块组成,第一个就是文件类,其下包含新建,打开,保存,另存为,退出,编辑类包含全部,剪切,粘贴,复制,格式包含自动换行和字体,查看包含状态栏,帮助关于作者信息。

其次对框架结构进行整理

可用6个类表示,即记事本的主菜单MainMenu,包括页面上的所有按钮

记事本的主程序(NotebookMain),字体部分对象(FontDialog),编码(Unicode),主面板(MainFrame)文件管理框架(FileOperator)

主程序NotebookMain

import javax.swing.*;
class Notebookmain {
    public static void main(String[] args) {
        try {
            String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
            UIManager.setLookAndFeel(lookAndFeel);//异常
        }catch (Exception e) {}
        MainFrame myFrame = new MainFrame();
        myFrame.setVisible(true);
    }
}

字体部分对象(FontDialog)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class FontDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    private static Font resultFont = null;
    JList listFontName, listFontStyle, listFontSize, listFontColor;
    JTextField editFontName, editFontStyle, editFontSize, editFontColor;
    String demoString;
    JLabel labelExample;
    JButton btnOK, btnCancel;
    Color[] colorArray = {Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY,
            Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA,
            Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW};
    String[] colorNameArray = {"BLACK", "BLUE", "CYAN", "DARK_GRAY", "GRAY",
            "GREEN", "LIGHT_GRAY", "MAGENTA", "ORANGE", "PINK", "RED", "WHITE",
            "YELLOW"};

    private JFrame frame;

    public FontDialog(JFrame owner, String title, boolean modal) {
        super(owner, title, modal);
        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        this.frame = owner;
        setLocationRelativeTo(owner);
        JPanel panelMain = new JPanel();
        panelMain.setLayout(new GridLayout(2, 1));
        JPanel panelFontSet, panelFontView;
        panelFontSet = new JPanel(new GridLayout(1, 4));
        panelFontView = new JPanel(new GridLayout(1, 2));
        demoString = "AaBbCcDdEe";
        labelExample = new JLabel(demoString, JLabel.CENTER);
        labelExample.setBackground(Color.WHITE);

        ListSelectionListener selectionListener = new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (((JList) e.getSource()).getName().equals("listFontName")) {
                    editFontName.setText((String) listFontName.getSelectedValue());
                    labelExample.setFont(new Font(editFontName.getText(), labelExample.getFont().getStyle(), labelExample.getFont().getSize()));
                }
                if (((JList) e.getSource()).getName().equals("listFontStyle")) {
                    editFontStyle.setText((String) listFontStyle.getSelectedValue());
                    labelExample.setFont(new Font(labelExample.getFont().getFontName(), listFontStyle.getSelectedIndex(), labelExample.getFont().getSize()));
                }
                if (((JList) e.getSource()).getName().equals("listFontSize")) {
                    editFontSize.setText((String) listFontSize.getSelectedValue());
                    try {
                        Integer.parseInt(editFontSize.getText());
                    } catch (Exception excepInt) {
                        editFontSize.setText(labelExample.getFont().getSize() + "");
                    }
                    labelExample.setFont(new Font(labelExample.getFont().getFontName(), labelExample.getFont().getStyle(), Integer.parseInt(editFontSize.getText())));
                }
                if (((JList) e.getSource()).getName().equals("listFontColor")) {
                    editFontColor.setText(colorNameArray[listFontColor.getSelectedIndex()]);
                    labelExample.setForeground(colorArray[listFontColor.getSelectedIndex()]);
                }
            }
        };

        KeyListener keyListener = new KeyListener() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    if (((JTextField) e.getSource()).getName().equals("listFontName")) {
                        labelExample.setFont(new Font(editFontName.getText(), labelExample.getFont().getStyle(), labelExample.getFont().getSize()));
                    }
                    if (((JTextField) e.getSource()).getName().equals("listFontStyle")) {
                        editFontStyle.setText((String) listFontStyle.getSelectedValue());
                        labelExample.setFont(new Font(labelExample.getFont().getFontName(), listFontStyle.getSelectedIndex(), labelExample.getFont().getSize()));
                    }
                    if (((JTextField) e.getSource()).getName().equals("listFontSize")) {
                        try {
                            Integer.parseInt(editFontSize.getText());
                        } catch (Exception excepInt) {
                            editFontSize.setText(labelExample.getFont().getSize() + "");
                        }
                        labelExample.setFont(new Font(labelExample.getFont().getFontName(), labelExample.getFont().getStyle(), Integer.parseInt(editFontSize.getText())));
                    }
                }
            }

            public void keyReleased(KeyEvent e) {
            }

            public void keyTyped(KeyEvent e) {
            }
        };
        JPanel panelFontName = new JPanel();
        Border border = BorderFactory.createLoweredBevelBorder();
        border = BorderFactory.createTitledBorder(border, "字体");
        panelFontName.setBorder(border);
        Font[] fontArray = java.awt.GraphicsEnvironment
                .getLocalGraphicsEnvironment().getAllFonts();
        int fontArrayCount = fontArray.length;
        String[] fontNameArray = new String[fontArrayCount];
        for (int i = 0; i < fontArrayCount; i++) {
            fontNameArray[i] = fontArray[i].getName();
        }
        listFontName = new JList(fontNameArray);
        listFontName.setName("listFontName");
        listFontName.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listFontName.addListSelectionListener(selectionListener);
        listFontName.setVisibleRowCount(6);
        editFontName = new JTextField(fontNameArray[0]);
        editFontName.setName("editFontName");
        editFontName.addKeyListener(keyListener);
        JScrollPane jspFontName = new JScrollPane(listFontName);
        panelFontName.setLayout(new BoxLayout(panelFontName, BoxLayout.PAGE_AXIS));
        panelFontName.add(editFontName);
        panelFontName.add(jspFontName);
        // 样式
        JPanel panelFontstyle = new JPanel();
        border = BorderFactory.createLoweredBevelBorder();
        border = BorderFactory.createTitledBorder(border, "样式");
        panelFontstyle.setBorder(border);
        String[] fontStylesArray = {"PLAIN", "BOLD", "ITALIC", "BOLD ITALIC"};
        listFontStyle = new JList(fontStylesArray);
        listFontStyle.setName("listFontStyle");
        listFontStyle.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listFontStyle.addListSelectionListener(selectionListener);
        listFontStyle.setVisibleRowCount(6);
        editFontStyle = new JTextField(fontStylesArray[0]);
        editFontStyle.setName("listFontStyle");
        editFontStyle.addKeyListener(keyListener);
        JScrollPane jspFontStyle = new JScrollPane(listFontStyle);
        panelFontstyle.setLayout(new BoxLayout(panelFontstyle, BoxLayout.PAGE_AXIS));
        panelFontstyle.add(editFontStyle);
        panelFontstyle.add(jspFontStyle);
        // 大小
        JPanel panelFontSize = new JPanel();
        border = BorderFactory.createLoweredBevelBorder();
        border = BorderFactory.createTitledBorder(border, "大小");
        panelFontSize.setBorder(border);
        String[] fontSizeArray = {"10", "14", "18", "22", "26", "30"};
        listFontSize = new JList(fontSizeArray);
        listFontSize.setName("listFontSize");
        listFontSize.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listFontSize.addListSelectionListener(selectionListener);
        listFontSize.setVisibleRowCount(6);
        editFontSize = new JTextField(fontSizeArray[0]);
        editFontSize.setName("listFontSize");
        editFontSize.addKeyListener(keyListener);
        JScrollPane jspFontSize = new JScrollPane(listFontSize);
        panelFontSize.setLayout(new BoxLayout(panelFontSize, BoxLayout.PAGE_AXIS));
        panelFontSize.add(editFontSize);
        panelFontSize.add(jspFontSize);
        // 颜色
        JPanel panelFontColor = new JPanel();
        Border borderColor = BorderFactory.createLoweredBevelBorder();
        borderColor = BorderFactory.createTitledBorder(borderColor, "颜色");
        panelFontColor.setBorder(borderColor);
        listFontColor = new JList(colorNameArray);
        listFontColor.setName("listFontColor");
        listFontColor.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listFontColor.addListSelectionListener(selectionListener);
        listFontColor.setVisibleRowCount(6);
        editFontColor = new JTextField(colorNameArray[0].toString());
        editFontColor.setName("editFontColor");
        editFontColor.addKeyListener(keyListener);
        JScrollPane jspFontColor = new JScrollPane(listFontColor);
        panelFontColor.setLayout(new BoxLayout(panelFontColor, BoxLayout.PAGE_AXIS));
        panelFontColor.add(editFontColor);
        panelFontColor.add(jspFontColor);
        panelFontSet.add(panelFontName);
        panelFontSet.add(panelFontstyle);//字体风格
        panelFontSet.add(panelFontSize);//字体的格式,粗细倾斜之类
        panelFontSet.add(panelFontColor);//字体颜色
        panelFontView.add(labelExample);
        panelMain.add(panelFontSet);
        panelMain.add(panelFontView);

        JPanel panelButton = new JPanel();
        panelButton.setLayout(new FlowLayout());
        btnOK = new JButton("确定");
        btnCancel = new JButton("取消");

        panelButton.add(btnOK);
        panelButton.add(btnCancel);

        btnOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                resultFont = labelExample.getFont();
                FontDialog.this.setVisible(false);
            }
        });
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                resultFont = null;
                FontDialog.this.setVisible(false);
            }
        });
        container.add(panelMain, BorderLayout.CENTER);
        container.add(panelButton, BorderLayout.SOUTH);
        setSize(400, 300);
        this.setVisible(true);
    }
    public static Font showDialog(JFrame owner, Font font) {
        FontDialog fontDialog = new FontDialog(owner, "字体设置", true);
        fontDialog.setVisible(true);
        return resultFont;
    }
}

文件管理框架(FileOperator)

import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
public class FileOperator {
    public static void main(String[] args) {
        System.out.println(selectFile("",JFileChooser.SAVE_DIALOG));
    }

    //打开文件对话框,返回已选择的文件名
    public static String selectFile(String pathFileName,int dialogType) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception e) {
            //...
        }
        // 创建文件选择器
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//只允许选择文件
        fileChooser.setMultiSelectionEnabled(false);//不允许多选
        // 设置当前目录
        if (!pathFileName.equals(""))
            fileChooser.setCurrentDirectory(new File(pathFileName));
        fileChooser.setAcceptAllFileFilterUsed(false);//先取消文件过滤器

        final String[][] fileExtNames = {
                {".cvs", "CVS文件(*.cvs)"},
                {".txt", "文本文档(*.txt)"}
        };

        // 显示所有文件
        fileChooser.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File file) {
                return true;
            }

            public String getDescription() {
                return "所有文件(*.*)";
            }
        });

        // 循环添加需要显示的文件
        for (final String[] fileExtName : fileExtNames) {
            fileChooser.setFileFilter(new FileFilter() {
                public boolean accept(File file) {
                    if (file.getName().toLowerCase().endsWith(fileExtName[0]) || file.isDirectory()) {
                        return true;
                    }
                    return false;
                }

                public String getDescription() {
                    return fileExtName[1];
                }
            });
        }

        fileChooser.setDialogType(dialogType);

        if (fileChooser.showDialog(null,null) ==JFileChooser.APPROVE_OPTION) {
            return fileChooser.getSelectedFile().getPath();
        } else {
            return "";//没有选择文件,比如取消了
        }
    }


    public static String readTxt(String path) {
        StringBuilder content = new StringBuilder("");
        try {
            String fileCharsetName = getFileCharsetName(path);
            //System.out.println("文件的编码格式为:"+fileCharsetName);

            InputStream is = new FileInputStream(path);
            //必须保证此处文件编码判断无误
            InputStreamReader isr = new InputStreamReader(is, fileCharsetName);
            BufferedReader br = new BufferedReader(isr);
            BufferedReader br2 = new BufferedReader(isr);
            String str = "";
            boolean isFirst = true;
            long start2 = System.currentTimeMillis();
            while (null != (str = br.readLine())) {
                if (!isFirst)
                    content.append(System.lineSeparator());
                else
                    isFirst = false;
                content.append(str);
            }
            long end2 = System.currentTimeMillis();
            System.out.println("charArray:"+(end2-start2));

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("读取文件:" + path + "失败!");
        }
        return content.toString();
    }

    public static boolean writeTxt(String path,String fileContent,String fileCharsetName) {
        boolean saveOK = false;
        try {

            OutputStream os = new FileOutputStream(path);
            //必须保证此处文件编码判断无误
            OutputStreamWriter osr = new OutputStreamWriter(os, fileCharsetName);
            BufferedWriter wr = new BufferedWriter(osr);

            wr.write(fileContent);
            wr.close();
            saveOK = true;
        } catch (Exception e) {
            System.err.println("文件存盘失败:" + path + "失败!"+e.getMessage());
        }
        return saveOK;
    }

    public static String getFileCharsetName(String fileName) throws IOException {
        String code = "UTF-8";
        try {
            code = EncodeUtils.getEncode(fileName, true);
            System.out.println(code);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }
}

编码(Unicode)

import java.io.*;
import java.util.BitSet;
public class EncodeUtils {
    private static int BYTE_SIZE = 8;
    public static String CODE_UTF8 = "UTF-8";
    public static String CODE_UTF8_BOM = "UTF-8_BOM";
    public static String CODE_GBK = "GBK";
    public static String getEncode(String fullFileName, boolean ignoreBom) throws Exception {
        //log.debug("fullFileName ; {}", fullFileName);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullFileName));
        return getEncode(bis, ignoreBom);
    }
    public static String getEncode(BufferedInputStream bis, boolean ignoreBom) throws Exception {
        bis.mark(0);
        String encodeType = "";
        byte[] head = new byte[3];
        bis.read(head);
        if (head[0] == -1 && head[1] == -2) {
            encodeType = "UTF-16";
        } else if (head[0] == -2 && head[1] == -1) {
            encodeType = "Unicode";
        } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) { //带BOM
            if (ignoreBom) {
                encodeType = CODE_UTF8;
            } else {
                encodeType = CODE_UTF8_BOM;
            }
        } else if ("Unicode".equals(encodeType)) {
            encodeType = "UTF-16";
        } else if (isUTF8(bis)) {
            encodeType = CODE_UTF8;
        } else {
            encodeType = CODE_GBK;
        }
        return encodeType;
    }
    private static boolean isUTF8(BufferedInputStream bis) throws Exception {
        bis.reset();
        //读取第一个字节
        int code = bis.read();
        do {
            BitSet bitSet = convert2BitSet(code);
            //判断是否为单字节
            if (bitSet.get(0)) {//多字节时,再读取N个字节
                if (!checkMultiByte(bis, bitSet)) {//未检测通过,直接返回
                    return false;
                }
            } else {
                //单字节时什么都不用做,再次读取字节
            }
            code = bis.read();
        } while (code != -1);
        return true;
    }
    private static boolean checkMultiByte(BufferedInputStream bis, BitSet bitSet) throws Exception {
        int count = getCountOfSequential(bitSet);
        byte[] bytes = new byte[count - 1];
        bis.read(bytes);
        for (byte b : bytes) {
            if (!checkUtf8Byte(b)) {
                return false;
            }
        }
        return true;
    }
    private static boolean checkUtf8Byte(byte b) throws Exception {
        BitSet bitSet = convert2BitSet(b);
        return bitSet.get(0) && !bitSet.get(1);
    }
    private static int getCountOfSequential(BitSet bitSet) {
        int count = 0;
        for (int i = 0; i < BYTE_SIZE; i++) {
            if (bitSet.get(i)) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }
    private static BitSet convert2BitSet(int code) {
        BitSet bitSet = new BitSet(BYTE_SIZE);
        for (int i = 0; i < BYTE_SIZE; i++) {
            int tmp3 = code >> (BYTE_SIZE - i - 1);
            int tmp2 = 0x1 & tmp3;
            if (tmp2 == 1) {
                bitSet.set(i);
            }
        }
        return bitSet;
    }
    public static void convert(String oldFullFileName, String oldCharsetName, String newFullFileName, String newCharsetName) throws Exception {
        StringBuffer content = new StringBuffer();

        BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(oldFullFileName), oldCharsetName));
        String line;
        while ((line = bin.readLine()) != null) {
            content.append(line);
            content.append(System.getProperty("line.separator"));
        }
        newFullFileName = newFullFileName.replace("\\", "/");
        File dir = new File(newFullFileName.substring(0, newFullFileName.lastIndexOf("/")));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Writer out = new OutputStreamWriter(new FileOutputStream(newFullFileName), newCharsetName);
        out.write(content.toString());
    }
}

主面板(MainFrame)

import java.awt.*;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class MainFrame extends JFrame {
    private Container container = this.getContentPane();
    private JTextArea textArea = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    private JPanel panelStatusBar = new JPanel(new BorderLayout(10,5));
    private JLabel labelContent = new JLabel("1行, 1列");
    private JLabel labelEncoding = new JLabel("字符编码:UTF-8  ");
    private MainMenu mainMenu;
    public void setCurrentFileCharset(String currentFileCharset) {
        labelEncoding.setText("字符编码:"+mainMenu.getCurrentFileCharset()+"  ");
    }
    private void updateStatusBar(CaretEvent e) {
        try {
            int caretPos = textArea.getCaretPosition(); //获取当前光标处出字符在textArea中的索引值
            int row = textArea.getLineOfOffset(caretPos); //算出行号
            int col = caretPos - textArea.getLineStartOffset(row); //算出列号
            labelContent.setText(String.format("%d行, %d列", row + 1, col + 1));
            labelContent.validate();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public MainFrame() {
        container.setLayout(new BorderLayout());
        initFrame();
        initTextArea();
        initStatusBar();
        initMenu();
    }
    private void initFrame() {
        setTitle("记事本");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口关闭方式
        setSize(800,535);
        setLocationRelativeTo(null); //居中显示
    }

    private void initMenu() {
        mainMenu = new MainMenu(this,textArea);
    }
    private void initTextArea() {
        textArea.setFont(new Font("新宋体",Font.ROMAN_BASELINE,14));
        textArea.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                mainMenu.setModified(true);
            }
            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                mainMenu.setModified(true);
            }
            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                mainMenu.setModified(true);
            }
        });
        textArea.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent e) {
                updateStatusBar(e);
            }
        });
        container.add(scrollPane,BorderLayout.CENTER);
        validate();
    }
    private void initStatusBar() {
        JLabel labelLeft = new JLabel("提示信息:");
        labelLeft.setHorizontalAlignment(SwingConstants.LEFT);
        labelContent.setHorizontalAlignment(SwingConstants.RIGHT);
        labelContent.setHorizontalAlignment(SwingConstants.LEFT);
        panelStatusBar.add(labelLeft,BorderLayout.WEST);
        panelStatusBar.add(labelContent,BorderLayout.CENTER);
        panelStatusBar.add(labelEncoding,BorderLayout.EAST);
        container.add(panelStatusBar,BorderLayout.SOUTH);
        validate();
    }
    public void setPanelStatusBarVisible(boolean visible) {
        this.panelStatusBar.setVisible(visible);
    }
}

主菜单(MainMenu)

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
/**主页面**/
public class MainMenu {
    private JFrame mainFrame = null;
    private JTextArea textArea = null;
    private String currentFileCharset = "UTF-8";//当前文件字符编码
    private String currentFileName = ""; //当前文件名
    private boolean isModified = false;//文件是否已修改
    public Clipboard clipboard = new Clipboard("系统剪切板");//剪贴板
    public boolean isModified() {
        return isModified;
    }
    public void setModified(boolean modified) {
        isModified = modified;
    }
    public void setCurrentFileCharset(String currentFileCharset) {
        this.currentFileCharset = currentFileCharset;
    }
    public String getCurrentFileCharset() {
        return currentFileCharset;
    }
    public MainMenu(JFrame owner, JTextArea textArea) {
        this.mainFrame = owner;
        this.textArea = textArea;
        initMenu();
    }

    private void initMenu() {
        JMenuBar menubar = new JMenuBar();//菜单条栏、菜单条:它是菜单的容器
        JMenu menuFile = new JMenu("文件(F)");
        JMenu menuEdit = new JMenu("编辑(E)");
        JMenu menuFormat = new JMenu("格式(O)");
        JMenu menuView = new JMenu("查看(V)");
        JMenu menuHelp = new JMenu("帮助(H)");
        menuFile.setMnemonic('F'); //设置菜单的热键为字母键F,需按下Alt键和字母键F
        menuEdit.setMnemonic('E');
        menuFormat.setMnemonic('O');
        menuView.setMnemonic('V');
        menuHelp.setMnemonic('H');

        menubar.add(menuFile); //把主菜单条加入菜单栏容器中
        menubar.add(menuEdit);
        menubar.add(menuFormat);
        menubar.add(menuView);
        menubar.add(menuHelp);

 /**文件的开始菜单**/
        JMenuItem miNew = new JMenuItem("新建(N)");
        miNew.setMnemonic('O');
        miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); //设置快捷键Ctrl_N
        miNew.addActionListener(this::menuFileActionPerformed);

        JMenuItem miOpen = new JMenuItem("打开(O)");
        miOpen.setMnemonic('O');
        miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); //设置快捷键Ctrl_O
        miOpen.addActionListener(this::menuFileActionPerformed);

        JMenuItem miSave=new JMenuItem("保存(S)");
        miSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); //设置快捷键Ctrl_S
        miSave.addActionListener(this::menuFileActionPerformed);

        JMenuItem miSaveAs = new JMenuItem("另存为(A)");
        miSaveAs.addActionListener(this::menuFileActionPerformed);

        JMenuItem miExit=new JMenuItem("退出(X)");
        miExit.addActionListener(this::menuFileActionPerformed);

        menuFile.add(miNew);
        menuFile.add(miOpen);
        menuFile.add(miSave);
        menuFile.add(miSaveAs);
        menuFile.addSeparator(); //分隔线
        menuFile.add(miExit);
/**文件end**/

        //---------------------------BEGIN 【编辑】菜单-----------------------//
        JMenuItem miSelectAll = new JMenuItem("全选(A)");
        miSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
        miSelectAll.addActionListener(this::menuEditActionPerformed);

        JMenuItem miCut=new JMenuItem("剪切(X)");
        miCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));
        miCut.addActionListener(this::menuEditActionPerformed);

        JMenuItem miCopy = new JMenuItem("复制(C)");
        miCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));
        miCopy.addActionListener(this::menuEditActionPerformed);

        JMenuItem miPaste=new JMenuItem("粘贴(V)");
        miPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));
        miPaste.addActionListener(this::menuEditActionPerformed);

        menuEdit.add(miSelectAll);
        menuEdit.addSeparator();
        menuEdit.add(miCut);
        menuEdit.add(miCopy);
        menuEdit.addSeparator();
        menuEdit.add(miPaste);
        //---------------------------END 【编辑】菜单-----------------------//

        //---------------------------BEGIN 【格式】菜单-----------------------//
        JCheckBoxMenuItem miAutoLine=new JCheckBoxMenuItem("自动换行(W)");
        textArea.setLineWrap(true);        //激活自动换行功能
        textArea.setWrapStyleWord(true);   //激活断行不断字功能
        miAutoLine.setState(textArea.getLineWrap());
        miAutoLine.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
        miAutoLine.addActionListener(this::menuFormatActionPerformed);

        JMenuItem miFontSet = new JMenuItem("字体(F)");
        miFontSet.setMnemonic('F');
        miFontSet.addActionListener(this::menuFormatActionPerformed);

        menuFormat.add(miAutoLine);
        menuFormat.add(miFontSet);
        //---------------------------END 【格式】菜单-----------------------//

        //---------------------------BEGIN 【查看】菜单-----------------------//
        JCheckBoxMenuItem miStatusBar=new JCheckBoxMenuItem("状态栏(S)");
        miStatusBar.setMnemonic('S');
        miStatusBar.setState(true);
        miStatusBar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ((MainFrame)mainFrame).setPanelStatusBarVisible(miStatusBar.getState());
                //自已加状态栏自已写
            }
        });

        menuView.add(miStatusBar);
        //---------------------------END 【查看】菜单-----------------------//


        //---------------------------BEGIN 【帮助】菜单-----------------------//
        JMenuItem miHelpContent = new JMenuItem("帮助信息……");
        miHelpContent.addActionListener(this::menuHelpActionPerformed);

        JMenuItem miAbout = new JMenuItem("关于……");
        miAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,Modifier.FINAL));
        miAbout.addActionListener(this::menuHelpActionPerformed);

        menuHelp.add(miHelpContent);
        menuHelp.addSeparator();
        menuHelp.add(miAbout);
        //---------------------------END 【帮助】菜单-----------------------//

        mainFrame.setJMenuBar(menubar);
        mainFrame.validate();
    }

    public void menuFileActionPerformed(ActionEvent e) {
        if (((JMenuItem)e.getSource()).getText().equals("新建(N)")) {
            if (canCloseFile()) {
                initVar();
            }
        }
        else if (((JMenuItem)e.getSource()).getText().equals("打开(O)")) {
            if (canCloseFile()) {
                openFile();
            }
        }
        else if (((JMenuItem)e.getSource()).getText().equals("保存(S)")) {
            //System.out.println(currentFileCharset);
            saveFile(currentFileName);
        }
        else if (((JMenuItem)e.getSource()).getText().equals("另存为(A)")) {
            saveFile("");
        }
        else if (((JMenuItem)e.getSource()).getText().equals("退出(X)")) {
            if (canCloseFile()) {
                System.exit(0);
            }
        }
    }

    public void menuEditActionPerformed(ActionEvent e) {
        if (((JMenuItem)e.getSource()).getText().equals("全选(A)")) {
            textArea.selectAll();
        }
        else if (((JMenuItem)e.getSource()).getText().equals("复制(C)")) {
            copy();
        }
        else if (((JMenuItem)e.getSource()).getText().equals("剪切(X)")) {
            cut();
        }
        else if (((JMenuItem)e.getSource()).getText().equals("粘贴(V)")) {
            paste();
        }
    }

    public void menuFormatActionPerformed(ActionEvent e) {
        if (((JMenuItem)e.getSource()).getText().equals("自动换行(W)")) {
            boolean bl = ((JCheckBoxMenuItem)e.getSource()).getState();
            textArea.setLineWrap(bl);        //激活自动换行功能
            textArea.setWrapStyleWord(bl);   //激活断行不断字功能
        }
        else if (((JMenuItem)e.getSource()).getText().equals("字体(F)")) {
            Font myFont = FontDialog.showDialog(mainFrame,textArea.getFont());
            if (myFont != null) {
                textArea.setFont(myFont);
            }
        }
    }

    public void menuHelpActionPerformed(ActionEvent e) {
        if (((JMenuItem)e.getSource()).getText().equals("帮助信息……")) {
            String str = "某理工大学数计学院\r\n"+
                    "计算机2102周**\r\n"+
                    "半月修改";
            JOptionPane.showMessageDialog(mainFrame, str,"帮助信息", 1);
        }
        else if (((JMenuItem)e.getSource()).getText().equals("关于……")) {
            String str = "某理工大学\r\n"+
                    "数计\r\n"+
                    "计算机2102周**";
            JOptionPane.showMessageDialog(mainFrame, str,"关于本程序……", 1);
        }
    }

    public void cut() {
        copy();
        //标记开始位置
        int start = this.textArea.getSelectionStart();
        //标记结束位置
        int end = this.textArea.getSelectionEnd();
        //删除所选段
        this.textArea.replaceRange("", start, end);

    }

    public void copy() {
        //拖动选取文本
        String temp = textArea.getSelectedText();
        //把获取的内容复制到连续字符器,这个类继承了剪贴板接口
        StringSelection text = new StringSelection(temp);
        //把内容放在剪贴板
        this.clipboard.setContents(text, null);
    }

    public void paste() {
        //Transferable接口,把剪贴板的内容转换成数据
        Transferable contents = this.clipboard.getContents(this);
        //DataFalvor类判断是否能把剪贴板的内容转换成所需数据类型
        DataFlavor flavor = DataFlavor.stringFlavor;
        //如果可以转换
        if (contents.isDataFlavorSupported(flavor)) {
            String str;
            try {//开始转换
                str = (String) contents.getTransferData(flavor);
                //如果要粘贴时,鼠标已经选中了一些字符
                if (this.textArea.getSelectedText() != null) {
                    //定位被选中字符的开始位置
                    int start = this.textArea.getSelectionStart();
                    //定位被选中字符的末尾位置
                    int end = this.textArea.getSelectionEnd();
                    //把粘贴的内容替换成被选中的内容
                    this.textArea.replaceRange(str, start, end);
                } else {
                    //获取鼠标所在TextArea的位置
                    int mouse = this.textArea.getCaretPosition();
                    //在鼠标所在的位置粘贴内容
                    this.textArea.insert(str, mouse);
                }
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private void initVar() { //初始化变量和文本框
        currentFileName = "";
        mainFrame.setTitle("记事本");
        isModified = false;
        currentFileCharset = "UTF-8";
        textArea.setText("");
    }
    private boolean openFile() {
        boolean isSucessed = false;
        String fn = FileOperator.selectFile(currentFileName,JFileChooser.OPEN_DIALOG);
        if (fn.equals("")) {
            return false;
        }
        try {
            String content = FileOperator.readTxt(fn);
            textArea.setText(content);
            currentFileName = fn;
            currentFileCharset = FileOperator.getFileCharsetName(fn);
            ((MainFrame)mainFrame).setCurrentFileCharset(currentFileCharset);
            isModified = false;
            mainFrame.setTitle(new File(currentFileName).getName());

            isSucessed = true;
        } catch (Exception ex) {
        }
        return isSucessed;
    }
    private boolean canCloseFile() {
        boolean canClose = true;
        if (isModified) {
            int n = JOptionPane.showConfirmDialog(null, "文件已修改但未保存,要保存吗?", "确认对话框", JOptionPane.YES_NO_CANCEL_OPTION);
            if (n == JOptionPane.YES_OPTION) {
                canClose = saveFile(currentFileName);
            } else if (n == JOptionPane.NO_OPTION) {
            } else {
                canClose = false;
            }
        }
        return canClose;
    }
    private boolean saveFile(String fn) {
        String fileName = fn;
        if (fileName.equals("")) {
            fileName = FileOperator.selectFile(currentFileName, JFileChooser.SAVE_DIALOG);
        }
        if (fileName.equals("")) {
            return false;
        }
        boolean saveOK = false;
        try {
            String content = textArea.getText();
            saveOK = FileOperator.writeTxt(fileName, content, currentFileCharset);
            if (saveOK) { // && !currentFileName.equals(fileName)) {
                currentFileName = fileName;
                isModified = false;
                currentFileCharset = FileOperator.getFileCharsetName(currentFileName);
                mainFrame.setTitle(new File(currentFileName).getName());
            } else {
                JOptionPane.showMessageDialog(null, "文件保存失败!\r\n", "系统提示",JOptionPane.ERROR_MESSAGE);
            }
        }catch (Exception e) {
        }
        return saveOK;
    }
}

运行结果:

 

 部分功能来源于网络搜集,仅供学习与交流

Part 2: Image Classification Project (50 marks) - Submission All of your dataset, code (Python files and ipynb files) should be a package in a single ZIP file, with a PDF of your report (notebook with output cells, analysis, and answers). INCLUDE your dataset in the zip file. For this project, you will develop an image classification model to recognize objects in your custom dataset. The project involves the following steps: Step 1: Dataset Creation (10 marks) • Task: You can choose an existing dataset such as FashionMNIST and add one more class. • Deliverable: Include the dataset (images and labels) in the ZIP file submission. Step 2: Data Loading and Exploration (10 marks) • Task: Organize the dataset into training, validation, and test sets. Display dataset statistics and visualize samples with their labels. For instance, show the number of data entries, the number of classes, the number of data entries for each class, the shape of the image size, and randomly plot 5 images in the training set with their corresponding labels. Step 3: Model Implementation (10 marks) • Task: Implement a classification model, using frameworks like TensorFlow or PyTorch. Existing models like EfficientNet are allowed. Provide details on model parameters. Step 4: Model Training (10 marks) • Task: Train the model with proper settings (e.g., epochs, optimizer, learning rate). Include visualizations of training and validation performance (loss and accuracy). Step 5: Model Evaluation and Testing (10 marks) • Task: Evaluate the model on the test set. Display sample predictions, calculate accuracy, and generate a confusion matrix.
07-28
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值