小米笔记 - 坏记性不如烂笔头

JAVA - 简单记事本

主要用到java.awt.、java.swing.、java.io.*这三个包,一共写了两个,第二个是最开始写的,我也发上来大家学习了。
还是很费脑筋的,记事本该有的功能都差不多有了。

第一个截图:

代码收好:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
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.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;


@SuppressWarnings("serial")
public class Test extends JFrame {
    // 添加属性
    private JComboBox combox_name, combox_size;// 字体、字号组合框
    private JButton button_larger,button_smaller,button_color;//字体变大变小和颜色选择器
    private JCheckBox checkb_bold, checkb_italic;// 粗体、斜体复选框
    private JPopupMenu popupmenu;
    private JTextArea ta = new JTextArea();
    private JScrollPane sp = new JScrollPane(ta);
    //查找对话框属性
    private JTextField tf_search;
    private JButton button_next;
    //
    private int key=0;

    public Test(String str) {
        super(str);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Dimension dim = getToolkit().getScreenSize(); // 获得屏幕分辨率
        this.setBounds(dim.width / 4, dim.height / 4, 700, 480);
        JToolBar toolbar = new JToolBar(); // 创建工具栏
        this.add(toolbar, BorderLayout.NORTH); // 工具栏添加到窗格北部
        this.add(sp);
        ta.setLineWrap(true);// 换行
        //////////////////字体
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontsName = ge.getAvailableFontFamilyNames(); // 获得系统字体
        combox_name = new JComboBox(fontsName);
        toolbar.add(combox_name);
        combox_name.addActionListener(new ActionListener() {// 字号
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize();
                ta.setFont(new Font(fontname, style, size));
            }
        });
        /////////////////字号
        String sizestr[] = { "20", "30", "40", "50", "60", "70" ,"80","90","100"};
        combox_size = new JComboBox(sizestr);
        combox_size.setEditable(true);
        toolbar.add(combox_size);
        combox_size.addActionListener(new ActionListener() {// 字号
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                int size = Integer.parseInt((String)combox_size.getSelectedItem());
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                ta.setFont(new Font(fontname, style, size));
            }
        });
        ////////////////////字号加减按钮
        button_larger=new JButton("A+");
        toolbar.add(button_larger);
        button_larger.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize()+5;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        button_smaller=new JButton("A-");
        toolbar.add(button_smaller);
        button_smaller.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize()-5;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        /////////////////J
        /////////////////粗体和斜体
        checkb_bold = new JCheckBox("粗体"); //字形复选框
        toolbar.add(checkb_bold);
        checkb_bold.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize();
                style = style ^ 1;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        checkb_italic = new JCheckBox("斜体");
        toolbar.add(checkb_italic);
        checkb_italic.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize();
                style = style ^ 2;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        ////////////////
        JRadioButton radiob_color[];
        String colorstr[]={"红","绿","蓝"};
        ButtonGroup bgroup_color = new ButtonGroup();      //按钮组
        radiob_color = new JRadioButton[colorstr.length];  //颜色单选按钮数组
        for (int i=0; i<radiob_color.length; i++){
            radiob_color[i]=new JRadioButton(colorstr[i]); 
            bgroup_color.add(radiob_color[i]); //添加到按钮组
            toolbar.add(radiob_color[i]);     //添加到工具栏
        }        
        radiob_color[0].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.red);// 设置颜色
            }
        });
        radiob_color[1].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.green);
            }
        });
        radiob_color[2].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.blue);
            }
        });
        ///////////////颜色选择器
        button_color=new JButton("其他");
        toolbar.add(button_color);
        button_color.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Color color;
                color=JColorChooser.showDialog(Test.this,"颜色选择", Color.black);
                ta.setForeground(color);// 设置颜色
            }
        });
        ////////////////鼠标事件
        ta.addMouseListener(new MouseAdapter() {// 鼠标事件处理方法,右击弹出菜单
            public void mouseClicked(MouseEvent e) {
                if (e.getModifiers() == MouseEvent.BUTTON3_MASK) // 单击的是鼠标右键
                    popupmenu.show(ta, e.getX(), e.getY()); // 在鼠标单击处显示快捷菜单
            }
        });
        ////////////////
        this.addmyMenu();       //调用自定义方法,添加菜单
        this.setVisible(true);
    }

    private void addmyMenu() {// 添加主菜单、快捷菜单、对话框
        JMenuBar menubar = new JMenuBar(); // 菜单栏
        this.setJMenuBar(menubar); // 添加菜单栏
        String menustr[] = { "文件", "编辑", "工具", "帮助" };
        JMenu menu[] = new JMenu[menustr.length];
        for (int i = 0; i < menustr.length; i++) {
            menu[i] = new JMenu(menustr[i]); // 菜单
            menubar.add(menu[i]); // 菜单栏中加入菜单
        }
        ////////////////////////////////
        JMenuItem menuitem_open = new JMenuItem("打开");
        menu[0].add(menuitem_open);
        menuitem_open.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser filechooser = new JFileChooser();
                int result = filechooser.showOpenDialog(Test.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File file = filechooser.getSelectedFile();
                        FileReader fr = new FileReader(file);
                        BufferedReader br = new BufferedReader(fr);
                        ta.setText("");
                        String text;
                        while ((text = br.readLine()) != null) {
                            ta.append(text);
                        }
                        fr.close();
                        br.close();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(Test.this,"打开文档出错!");
                    }
                }
            }
        });
        JMenuItem menuitem_save = new JMenuItem("保存");
        menu[0].add(menuitem_save);
        menuitem_save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser filechooser = new JFileChooser();
                int result = filechooser.showSaveDialog(Test.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File file = filechooser.getSelectedFile();
                        FileWriter fw = new FileWriter(file);
                        BufferedWriter bw = new BufferedWriter(fw);
                        String text=ta.getText();
                        fw.write(text);
                        fw.close();
                        bw.close();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(Test.this,"打开文档出错!");
                    }
                }

            }
        });
        menu[0].addSeparator(); // 加分隔线
        JMenuItem menuitem_exit = new JMenuItem("退出");
        menu[0].add(menuitem_exit);
        menuitem_exit.addActionListener(new ActionListener() {// 退出
                    public void actionPerformed(ActionEvent e) {
                        System.exit(0);
                    }
                });
        /////////////////////////////
        JMenu menu_style = new JMenu("字形");
        JCheckBoxMenuItem checkboxmenuitem_bold = new JCheckBoxMenuItem("粗体");
        menu_style.add(checkboxmenuitem_bold);
        JCheckBoxMenuItem checkboxmenuitem_italic = new JCheckBoxMenuItem("斜体");
        menu_style.add(checkboxmenuitem_italic);
        menu[1].add(menu_style); // 菜单加入到菜单中成为二级菜单
        checkboxmenuitem_bold.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize();
                style = style ^ 1;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        
        checkboxmenuitem_italic.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String fontname = (String)combox_name.getSelectedItem();//获得字体名
                Font font = ta.getFont();     //获得文本区的当前字体对象
                int style = font.getStyle();      //获得字形
                int size = font.getSize();
                style = style ^ 2;
                ta.setFont(new Font(fontname, style, size));
            }
        });
        ////////////////////////////
        JMenu menu_color = new JMenu("颜色");
        menu[1].add(menu_color);
        ButtonGroup buttongroup = new ButtonGroup();
        String colorstr[] = { "红", "绿", "蓝" };
        JRadioButtonMenuItem rbmi_color[] = new JRadioButtonMenuItem[colorstr.length];
        for (int i = 0; i < rbmi_color.length; i++) {
            rbmi_color[i] = new JRadioButtonMenuItem(colorstr[i]); // 单选菜单项
            buttongroup.add(rbmi_color[i]);
            menu_color.add(rbmi_color[i]);
        }
        rbmi_color[0].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.red);
            }
        });
        rbmi_color[1].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.green);
            }
        });
        rbmi_color[2].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.setForeground(Color.blue);
            }
        });
        /////////////////////////////////
        JMenuItem menuitem_countwordsnum = new JMenuItem("字数统计");
        menu[2].add(menuitem_countwordsnum);
        menuitem_countwordsnum.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int count=0;
                for(int i=0;i<ta.getText().length();i++){
                    if(!ta.getText().substring(i,i+1).equals(" ")){
                        count++;
                    }
                }
                JOptionPane.showMessageDialog(Test.this, "文本框中一共有"+count+"个字符!");
            }
        });
        menu[2].addSeparator(); // 加分隔线
        JMenuItem menuitem_search = new JMenuItem("查找");
        menu[2].add(menuitem_search);
        menuitem_search.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new MessageJDialog();
                
                button_next.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String str_search=tf_search.getText();
                        int len = str_search.length();
                        for (int i = key; i < ta.getText().length() - len + 1; i++) {
                            String str_record = ta.getText().substring(i, i + len);
                            if (str_record.equals(str_search)) {
                                key = i + 1;
                                ta.requestFocus();
                                ta.select(i, i + len);
                                return;
                            }
                        }
                    }
                });
                
                key=0;
            }
        });
        JMenuItem menuitem_replace = new JMenuItem("替换");
        menu[2].add(menuitem_replace);
        menuitem_replace.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str_replace=JOptionPane.showInputDialog(Test.this,
                        "请输入你要替换的字符串:" );
                String str_replacelater=JOptionPane.showInputDialog(Test.this,
                        "请输入你要用来替换的内容:" );
                int len=str_replace.length();
                for(int i=0;i<ta.getText().length()-len+1;i++){
                    String str_record=ta.getText().substring(i, i+len);
                    if(str_record.equals(str_replace)){
                        ta.replaceRange(str_replacelater,i, i+len);
                    }
                }
            }
        });
        /////////////////////////////////
        JMenuItem menuitem_about = new JMenuItem("关于");
        menu[3].add(menuitem_about);
        menuitem_about.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(Test.this,"文本编辑器v1.0   开发者:Mi");
            }
        });
        ////////////////////////////////////////////////// 快捷菜单对象
        popupmenu = new JPopupMenu();
        String menuitemstr[] = { "剪切", "复制", "粘贴" };
        JMenuItem popmenuitem[] = new JMenuItem[menuitemstr.length];
        for (int i = 0; i < popmenuitem.length; i++) {
            popmenuitem[i] = new JMenuItem(menuitemstr[i]);// 菜单项
            popupmenu.add(popmenuitem[i]);// 快捷菜单加入菜单项
        }
        popmenuitem[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
                InputEvent.CTRL_MASK));// 设置快捷键Ctrl+X
        popmenuitem[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
                InputEvent.CTRL_MASK));// 设置快捷键Ctrl+C
        popmenuitem[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
                InputEvent.CTRL_MASK));// 设置快捷键Ctrl+V

        popmenuitem[0].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.cut(); //将选中文本剪切送系统剪贴板
            }
        });
        popmenuitem[1].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.copy(); //将选中文本复制送系统剪贴板
            }
        });
        popmenuitem[2].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ta.paste();//剪贴板的文本粘贴在当前位置
            }
        });
        ta.add(popupmenu); // 文本区添加快捷菜单
    }

    //
    private class MessageJDialog extends JDialog {
        private JLabel lable_tip;
        private JPanel panel_next = new JPanel();
        private JPanel panel_search = new JPanel();
        private JPanel panel_tip = new JPanel();

        public MessageJDialog() {
            super(Test.this, "查找");
            this.setSize(300, 170);
            this.setLocation(Test.this.getX() + 200,
                    Test.this.getY() + 200);
            this.setLayout(new GridLayout(3, 1));
            //
            ImageIcon imageIcon = new ImageIcon("img/search.png");
            lable_tip = new JLabel("请输入你要查找的字符串:", imageIcon, JLabel.LEFT);
            panel_tip.add(lable_tip);
            this.add(panel_tip);
            tf_search = new JTextField(20);
            panel_search.add(tf_search);
            this.add(panel_search);
            button_next = new JButton("查找下一个");
            panel_next.add(button_next);
            this.add(panel_next);
            this.setVisible(true);
        }
    }
    
    public static void main(String args[]) {
        new Test("文本编辑器v1.0");
    }
}

第二个截图:

这个就写得乱点,第一次写的,功能和上个差不多,但一些功能的实现方法就不一样了,发出来大家学习下。
代码如下:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JColorChooser;
import javax.swing.JComboBox;
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.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.FontUIResource;


public final class NotePad implements ActionListener {

    private JFrame frame;
    private JPanel panel;
    private JTextArea textArea;//文本区
    private JScrollPane scrollPane;
    /*菜单*/
    private JMenuBar menuBar;
    private JMenu menuFile,menuOption,menuHelp,menuColor;
    private JMenuItem miFileOpen,miFileSave,miFileExit,miHelpAbout,miColorForeground,miColorBackground,miPopCopy,miPopPaste;
    //private JToolBar toolBar;
    /*字体背景*/
    private JLabel lblFontFamily,lblFontsize;
    private JComboBox cBoxFontFamily,cBoxFontSize;
    private Color bColor,fColor;
    private Font font;
    
    private JPopupMenu popupMenu;
    
    public NotePad() {
        frame = new JFrame("记事本");
        panel = new JPanel(new BorderLayout());
        textArea = new JTextArea(20,10);
        scrollPane = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        textArea.setLineWrap(true);//输入框中文本自动换行
        
        //初始字体
        font = new Font("宋体",Font.BOLD,20);
        textArea.setFont(font);
        
        //右键弹出菜单
        popupMenu = new JPopupMenu();
        miPopCopy = new JMenuItem("复制");
        miPopPaste = new JMenuItem("粘贴");
        popupMenu.add(miPopCopy);
        popupMenu.add(miPopPaste);
        
        //文本区textArea->scrollPanel->panel
        
        //scrollPane.add(textArea);
        panel.add(scrollPane,BorderLayout.CENTER);
        //frame.add(Panel,BorderLayout.CENTER);
        /*菜单实例化*/
        menuBar = new JMenuBar();
        menuFile = new JMenu("File");
        miFileOpen = new JMenuItem("Open");
        miFileSave = new JMenuItem("Save");
        miFileExit = new JMenuItem("Exit");
        menuOption = new JMenu("Option");
        menuColor = new JMenu("Color");
        miColorForeground = new JMenuItem("Foreground");
        miColorBackground = new JMenuItem("Background");
        menuHelp = new JMenu("Help");
        miHelpAbout = new JMenuItem("About");
        /*工具栏*/
        JToolBar jToolBar = new JToolBar(JToolBar.HORIZONTAL);//创建工具栏,横向排列   orientation 排列方式
        jToolBar.setFloatable(true);//工具栏可以拖动
        /*字体样式方法*/
        lblFontFamily = new JLabel("字体");
        lblFontsize = new JLabel("字号");
        String []items;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        items = ge.getAvailableFontFamilyNames();
        cBoxFontFamily = new JComboBox(items);
        cBoxFontFamily.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                
            }
        });
        /*字体大小*/
        String []items2 = {"5","10","20", "30", "40", "50", "60", "70" ,"80","90","100"};
        cBoxFontSize = new JComboBox(items2);
        
        cBoxFontFamily.setPreferredSize(new Dimension(20,30));//Cbox框大小调整
        cBoxFontSize.setPreferredSize(new Dimension(20,30));
        jToolBar.add(lblFontFamily);
        jToolBar.add(cBoxFontFamily);
        jToolBar.add(lblFontsize);
        jToolBar.add(cBoxFontSize);
        panel.add(jToolBar,BorderLayout.NORTH);

        /*菜单栏Open*/
        menuBar.add(menuFile);
        menuFile.add(miFileOpen);
        menuFile.addSeparator();
        menuFile.add(miFileSave);
        menuFile.addSeparator();
        menuFile.add(miFileExit);
        /*菜单栏Option*/
        menuBar.add(menuOption);
        menuOption.add(menuColor);
        menuColor.add(miColorForeground);
        menuColor.add(miColorBackground);
        /*菜单栏Help*/
        menuBar.add(menuHelp);
        menuHelp.add(miHelpAbout);
        /*组合键和快捷键*/
        menuFile.setMnemonic(KeyEvent.VK_F);//快捷键
        menuOption.setMnemonic(KeyEvent.VK_O);
        miFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));//组合键
        miFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        menuHelp.setMnemonic(KeyEvent.VK_H);
        
        
        /*添加监听器*/
        miHelpAbout.addActionListener(this);
        miColorBackground.addActionListener(this);
        miColorForeground.addActionListener(this);
        miFileOpen.addActionListener(this);
        miFileSave.addActionListener(this);
        miFileExit.addActionListener(this);
        miPopCopy.addActionListener(this);
        miPopPaste.addActionListener(this);
        
        cBoxFontFamily.addItemListener(itemListener);
        cBoxFontSize.addItemListener(itemListener);
        
        //事件处理方式3    :事件适配器Adapter
        textArea.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                super.mouseReleased(e);
                if (e.isPopupTrigger()) // 单击的是鼠标右键
                    popupMenu.show(e.getComponent(), e.getX(), e.getY()); // 在鼠标单击处显示快捷菜单
            }
        });
        frame.setJMenuBar(menuBar);
        frame.setVisible(true);
        frame.setSize(600,400);
        frame.setContentPane(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    //处理事件方式2
    private ItemListener itemListener = new ItemListener() {
        
        public void itemStateChanged(ItemEvent e) {
            //字体
            if (e.getSource().equals(cBoxFontFamily)) {
                font = new Font(e.getItem().toString(), font.getStyle(),font.getSize());
                textArea.setFont(font);
            }
            //字号
            if (e.getSource().equals(cBoxFontSize)) {
                //System.out.println(e.getItem());
                font = new FontUIResource(font.getFamily(), font.getStyle(), Integer.parseInt(e.getItem().toString()));
                textArea.setFont(font);
            }
            
        }
    };
    

    public void actionPerformed(ActionEvent e) {
        //判断事件源
        //帮助
        if (e.getSource().equals(miHelpAbout)) {
            JOptionPane.showMessageDialog(frame, "2015.6.8");
        }
        //背景色
        if (e.getSource().equals(miColorBackground)) {
            bColor = JColorChooser.showDialog(frame, "背景色", Color.BLUE);
            textArea.setBackground(bColor);
        }
        //前景色
        if (e.getSource().equals(miColorForeground)) {
            fColor = JColorChooser.showDialog(frame, "前景色", Color.BLACK);
            textArea.setForeground(fColor);
        }
        //打开    JFileChooser
        //Fileter:过滤器        FileFilter:文件过滤器
        if (e.getSource().equals(miFileOpen)) {
            JFileChooser filechooser = new JFileChooser("C:\\Users\\Administrator\\Desktop");
            FileFilter filter = new MyFileFilter();
            filechooser.setFileFilter(filter);
            int result = filechooser.showOpenDialog(frame);
            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    File file = filechooser.getSelectedFile();
                    FileReader fr = new FileReader(file);
                    BufferedReader br = new BufferedReader(fr);
                    textArea.setText("");
                    String text;
                    while ((text = br.readLine()) != null) {
                        textArea.append(text);
                    }
                    fr.close();
                    br.close();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame,"打开文档出错!");
                }
            }
        }
        //保存
        if (e.getSource().equals(miFileSave)) {
            JFileChooser filechooser = new JFileChooser("C:\\Users\\Administrator\\Desktop");
            FileFilter filter = new MyFileFilter();
            filechooser.setFileFilter(filter);
            int result = filechooser.showSaveDialog(frame);
            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    File file = filechooser.getSelectedFile();
                    FileWriter fw = new FileWriter(file);
                    BufferedWriter bw = new BufferedWriter(fw);
                    String text=textArea.getText();
                    fw.write(text);
                    fw.close();
                    bw.close();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame,"保存文档出错!");
                }
            }
        }
        //退出
        if (e.getSource().equals(miFileExit)) {
            System.exit(0);
        }
        //复制
        if (e.getSource().equals(miPopCopy)) {
            textArea.copy();
        }
        //粘贴
        if (e.getSource().equals(miPopPaste)) {
            textArea.paste();
        }
    }
    
    public static void main(String[] args) {
        new NotePad();
    }

}

class MyFileFilter extends FileFilter{

    //定义过滤器    过滤.txt
    public boolean israr(File file){
        return file.getName().endsWith(".rar");
    }
    public boolean istxt(File file){
        return file.getName().endsWith(".txt");
    }
    public boolean isyinpin(File file){
        return file.getName().endsWith(".mp3")
                ||file.getName().endsWith(".midi")
                ||file.getName().endsWith(".wav");
    }
    public boolean accept(File f) {
        // TODO Auto-generated method stub
        return israr(f)||istxt(f)||isyinpin(f);
    }
    /*
    public boolean accept(File f) {
        // TODO Auto-generated method stub
        return f.getName().toLowerCase().endsWith(".txt")
                ||f.getName().toLowerCase().endsWith(".mp3")
                ||f.getName().toLowerCase().endsWith(".midi")
                ||f.getName().toLowerCase().endsWith(".wav");//过滤文件名.TXT.txt结尾
    }
    */
    //过滤器的描述
    public String getDescription() {
        // TODO Auto-generated method stub
        return ".txt,.mp3,.midi,.wav";
    }
    public String getDescription2() {
        // TODO Auto-generated method stub
        return ".txt,.mp3,.midi,.wav";
    }
    
}

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »