记事本代码

记事本代码

如下:

package 记事本;

 

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.Frame;

import java.awt.GraphicsEnvironment;

import java.awt.Rectangle;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Reader;

import java.io.Writer;

import java.nio.CharBuffer;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

import java.util.Vector;

import java.util.regex.Pattern;

 

import javax.swing.BorderFactory;

import javax.swing.JButton;

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.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JSplitPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.event.CaretEvent;

import javax.swing.event.CaretListener;

import javax.swing.event.UndoableEditEvent;

import javax.swing.event.UndoableEditListener;

import javax.swing.undo.UndoManager;

 

 

 

public class Notepad implements ActionListener {

 

    String time; //当前时间的字符串形式

    

    int frameSum=1; //记事本框架上的框架总数

    int fontSizeNum=20; //代表字体尺寸的数字

    int fontStyle=Font.CENTER_BASELINE; //代表字体风格的常量

    String fontTypefaceNum="华文行楷"; //代表字体的字体值的字符串

    String fontColorNum="black"; //代表字体颜色值得字符串

 

    File inOutFile; //记事本的输入输出文件

    File attributeFile; //记事本的属性的文件

    Font font=null; //记事本文本框的显示字体对象

    

    JFrame frame; //记事本主要框架

    JTextArea textArea; //记事本文本域 添加在滚动条面板中

    JSplitPane splitPane; //记事本主体面板 分割型面板

    JTabbedPane tabbedPane; //记事本分割面板的上部分

    JPanel lowerPanel; //记事本分割面板的下部分

    JScrollPane scrollPane; //滚动条面板 添加在分割面板的下部分中的中区域

    JPanel panelOption; //普通面板 添加在选项卡面板中的第一个选项中

    JPanel panelFont; //普通面板 添加在选项卡面板中的第二个选项中

    JPanel panelUndo; //普通面板 添加在选项卡面板中的第三个选项中

    JPanel statePanel; //状态面板 添加在分割面板的下部分中的南区域

    

    JLabel wordNumber; //字数标签

    JLabel lineRowLabel; //显示行列的标签

    JLabel fontSizeNumLabel; //显示字体大小值的标签

    JLabel fontColorNumLabel; //显示字体颜色值的标签

    JLabel fontTypefaceNumLabel; //显示字体的字体的标签

    JLabel timeLabel; //时间标签

    

    UndoManager um; //撤销管理器

    

    JButton newWindow; //按钮 新窗口

    JButton createNewTxt; //按钮 创建新文本

    JButton openFile; //按钮 打开文本文件

    JButton saveFile; //按钮 保存文件

    JButton preservationFile; //按钮 另存为其他文件

    JButton revoke; //按钮 撤销

    JButton recovery; //恢复

    JButton fontColor; //按钮 设置字体颜色

    JButton fontSize; //按钮 设置字体尺寸大小

    JButton fontTypeface; //按钮 设置字体的字体

    

    static int notepadFrameSum=0; //记事本框架总数

    static String[] fonts=null; //本机所有可用字体

    static String[] colors= {"black","blue","cyan","darkGray","gray","green","lightGray","magenta","orange","pink","red","white"}; //所有可使用的字体颜色

//    static String[] fontSizeNums= {"1","5","10","20","25","30","35","36","37","38","39","40","41","42","43","44","45","50"};

    static String parentsPath="C:"+File.separator+"Users"+File.separator+"ASUS"+File.separator+"Desktop"+File.separator+"java作业"+File.separator+"记事本"; //记事本用来保存内容的父路径

    static String attributePath="C:"+File.separator+"Users"+File.separator+"ASUS"+File.separator+"Desktop"+File.separator+"java作业"+File.separator+"记事本属性";//记事本用来保存文本属性的父路径

    

    public Notepad() { //构造方法

        notepadFrameSum++; //每创建一个新的Notepad类,记事本框架数加一

        getNativeFont(); //获得本机全部可用字体

        notepad(); //记事本初始化方法

    }

    

    public String[] getNativeFont() { //得到本机所有可用字体

        if(Notepad.fonts==null) {

            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

            Notepad.fonts=ge.getAvailableFontFamilyNames();

        }

     return Notepad.fonts;

    }

    

    public void notepad() { //记事本主体方法

        this.frame=new JFrame("记事本");

        this.textArea=new JTextArea(inputFile()); //设置文本域中的的文本为 输入文件内保存的内容

        

        //面板

this.tabbedPane=new JTabbedPane(JTabbedPane.TOP); //选项卡面板,置顶分布选项卡

        this.lowerPanel=new JPanel(new BorderLayout()); //普通面板 采用区域布局

        this.splitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,tabbedPane,lowerPanel); //分隔面板,垂直分割,分隔条改变时重画分隔条两端,上部分选项卡面板,下部分为简单面板

        this.statePanel=new JPanel(); //普通面板 显示状态

        this.scrollPane=new JScrollPane(textArea); //滚动条面板,给文本域设置滚动条

        this.panelOption=new JPanel(new FlowLayout(FlowLayout.LEFT)); //选项面板,对齐方式为左对齐

        this.panelFont=new JPanel(new FlowLayout(FlowLayout.LEFT)); //字体面板,对齐方式为左对齐

        this.panelUndo=new JPanel(new FlowLayout(FlowLayout.LEFT)); //撤销面板,对齐方式为左对齐

        

        //字体

        this.font=new Font(this.fontTypefaceNum, this.fontStyle, this.fontSizeNum); //字体初始化

        

        //标签

        this.timeLabel=new JLabel("");

        this.wordNumber=new JLabel("");

        this.lineRowLabel=new JLabel("未知");

        this.fontSizeNumLabel=new JLabel("字体大小:"+this.fontSizeNum);

        this.fontColorNumLabel=new JLabel("字体颜色:"+this.fontColorNum);

        this.fontTypefaceNumLabel=new JLabel("字体:"+this.fontTypefaceNum);

        

        //全部按钮

        this.newWindow=new JButton("新窗口(N)");

        this.createNewTxt=new JButton("新建(C)");

        this.openFile=new JButton("打开(O)");

        this.saveFile=new JButton("保存(S)");

        this.preservationFile=new JButton("另存为(p)");

        this.revoke=new JButton("撤销(Z)");

        this.recovery=new JButton("恢复(Y)");

        this.um=new UndoManager();

        this.fontColor=new JButton("颜色");

        this.fontSize=new JButton("大小");

        this.fontTypeface=new JButton("字体");

        

        //按钮添加活动监听和快捷键

        fontColor.addActionListener(this);

        fontSize.addActionListener(this);

        fontTypeface.addActionListener(this);

        

        openFile.addActionListener(this);

        openFile.setMnemonic(KeyEvent.VK_O);

        createNewTxt.addActionListener(this);

        createNewTxt.setMnemonic(KeyEvent.VK_C);

        saveFile.addActionListener(this);

        saveFile.setMnemonic(KeyEvent.VK_S);

        preservationFile.addActionListener(this);

        preservationFile.setMnemonic(KeyEvent.VK_P);

        newWindow.addActionListener(this);

        newWindow.setMnemonic(KeyEvent.VK_N);

        revoke.addActionListener(this);

        revoke.setMnemonic(KeyEvent.VK_Z);

        recovery.addActionListener(this);

        recovery.setMnemonic(KeyEvent.VK_Y);

        

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //设置框架默认关闭策略,最后一个框架关闭时,程序终止

        frame.setTitle("记事本."+inOutFile.getName()); //框架标题,方便用户知道正在操作哪个文本文件

        splitPane.setDividerLocation(0.2); //分割条位置

        frame.setSize(600, 400);

        frame.setLocation(400, 200);

        frame.setVisible(true);

        textArea.setLineWrap(true); //自动换行

        textArea.setFont(font);

        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //水平滚动条何时出现在滚动条面板中,策略为按需要出现

        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); //垂直滚动条何时出现在滚动条面板中,策略为按需要出现

        

        //将按钮添加到各自所属面板中

        //选项面板

        panelOption.add(newWindow);

        panelOption.add(createNewTxt);

        panelOption.add(openFile);

        panelOption.add(saveFile);

        panelOption.add(preservationFile);

        

        //字体面板

        panelFont.add(fontSize);

        panelFont.add(fontColor);

        panelFont.add(fontTypeface);

        

        //撤销面板

        panelUndo.add(revoke);

        panelUndo.add(recovery);

        

        //添加选项卡

tabbedPane.addTab("选项",panelOption);

tabbedPane.addTab("字体",panelFont);

tabbedPane.addTab("UNDO", panelUndo);

 

 

//添加到属性面板

statePanel.add(wordNumber);

statePanel.add(lineRowLabel);

        statePanel.add(fontSizeNumLabel);

        statePanel.add(fontColorNumLabel);

        statePanel.add(fontTypefaceNumLabel);

        statePanel.add(timeLabel);

        

        

        //主面板添加

lowerPanel.add(statePanel,BorderLayout.SOUTH);

lowerPanel.add(scrollPane,BorderLayout.CENTER);

        frame.add(splitPane);

        

        textArea.getDocument().addUndoableEditListener(um); //添加可撤销的编辑监听器

textArea.addCaretListener(new CaretListener() { //添加光标监听

            @Override

            public void caretUpdate(CaretEvent e) {

                // TODO Auto-generated method stub

             try {

             int pos = textArea.getCaretPosition(); //获取行数

int lineOfC = textArea.getLineOfOffset(pos) + 1; //获取列数

int col = pos - textArea.getLineStartOffset(lineOfC - 1) + 1;

wordNumber.setText("字数:"+textArea.getText().length());

lineRowLabel.setText( "当前位置: " + lineOfC + "行" + col + "列 ");

             }catch(Exception e1){

             }

            }

        });

        

        frame.addWindowListener(new WindowAdapter() { //添加窗口监听,参数为窗口适配器,覆写需要的监听事件及对应的行为,等效于下面那个方法

            @Override

            public void windowClosing(WindowEvent e) {

             outputFile(textArea.getText());

             notepadFrameSum--;

             if(notepadFrameSum<=0) {

                 System.exit(1);

             }

            }

        });

        configTime(); //显示时间

        attributeRead(); //属性恢复

        changeStateLabel();//改变属性标签

    }

    

    @Override

    public void actionPerformed(ActionEvent e) { //主页面按钮活动执行方法

        // TODO Auto-generated method stub

        if(e.getSource() instanceof JButton&&this.frameSum==1) {

            this.frameSum++;

            if(e.getSource()==this.fontColor) {

                changeColor();

            }else if(e.getSource()==this.fontSize) {

                changeFontSize();

            }else if(e.getSource()==this.fontTypeface) {

                changeFontTypeface();

            }else if(e.getSource()==this.openFile) {

                outputFile(this.textArea.getText());

                inputFile(openNewFile());

                frame.setTitle("记事本."+inOutFile.getName());

            }else if(e.getSource()==this.createNewTxt) {

                outputFile(this.textArea.getText());

                createTxt();

            }else if(e.getSource()==this.preservationFile) {

                outputFile(this.textArea.getText());

                saveFile();

            }else if(e.getSource()==this.newWindow) {

                this.frameSum--;

                new Notepad().createTxt();

            }else if(e.getSource()==this.revoke) {

                this.frameSum--;

                if (um.canUndo()) {

um.undo();

}

            }else if(e.getSource()==this.recovery) {

                this.frameSum--;

                 if (um.canRedo()) {

     um.redo();

     }

            }else if(e.getSource()==this.saveFile) {

                this.frameSum--;

                outputFile(this.textArea.getText());

                 promptLabel();

            }

        }

    }

    

    public void changeStateLabel() { //改变状态标签的方法

        this.fontSizeNumLabel.setText("字体大小:"+this.fontSizeNum);

        this.fontColorNumLabel.setText("字体颜色:"+this.fontColorNum);

        this.fontTypefaceNumLabel.setText("字体:"+this.fontTypefaceNum);

    }

    

    void configTime() { //时间更新

        Timer tmr = new Timer();

        tmr.scheduleAtFixedRate(new JLabelTimerTask(), new Date(), 1000); //以固定1000毫秒频率执行线程

    }

    protected class JLabelTimerTask extends TimerTask { //被执行的线程类

        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        public void run() {

            time = dateFormatter.format(Calendar.getInstance().getTime());

            timeLabel.setText(time);

        }

    }

    

    public void attributeSave() { //属性保存

        this.attributeFile=new File(Notepad.attributePath);

        if(!this.attributeFile.isDirectory()) {

            this.attributeFile.mkdirs();

        }

        this.attributeFile=new File(Notepad.attributePath+File.separator+this.inOutFile.getName());

        if(!this.attributeFile.exists()) {

            try {

                this.attributeFile.createNewFile();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

        try {

            Writer output=new FileWriter(this.attributeFile);

            output.write(fontSizeNum+"\n"+fontColorNum+"\n"+fontTypefaceNum+"\n"+fontStyle+"\n");

            output.close();

            System.out.println("属性保存成功");

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    

    public void attributeRead() { //属性恢复

        this.attributeFile=new File(Notepad.attributePath+File.separator+this.inOutFile.getName());

        if(!this.attributeFile.exists()) {

            try {

                this.attributeFile.createNewFile();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            attributeSave();

            return;

        }else {

            try {

                Reader input=new FileReader(attributeFile);

                int c;

                for(int i=0;i<4;i++) {

                    char ch[]=new char[1024];

                    int x=0;

                    while((c=input.read())!='\n'&&c!=-1) {

                        ch[x]=(char)c;

                        x++;

                    }

                    if(i==0) {

                        this.fontSizeNum=Integer.parseInt(new String(ch,0,x));

                    }else if(i==1) {

                        this.fontColorNum=new String(ch,0,x);

                    }else if(i==2) {

                        this.fontTypefaceNum=new String(ch,0,x);

                    }else {

                        this.fontStyle=Integer.parseInt(new String(ch,0,x));

                    }

                }

                this.textArea.setFont(new Font(this.fontTypefaceNum,this.fontStyle, this.fontSizeNum));

                this.textArea.setForeground(judge(this.fontColorNum));

                input.close();

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }    

        }

        

    }

    

    public String inputFile() { //初始化文件输入方法

        StringBuffer path=new StringBuffer(Notepad.parentsPath);

        File file =new File(path.toString());

        File[] sonFiles=null;

        

        if(!file.isDirectory()) {

            try {

                file.mkdirs();

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

        if(file.listFiles().length==0) {

            sonFiles=new File[3];

            path.append(File.separator+"1.txt");

            File fileOne=new File(path.toString());

            try {

                fileOne.createNewFile();

                sonFiles[0]=fileOne;

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }else {

            sonFiles=file.listFiles();

        }

        

        this.inOutFile=sonFiles[0];

        char[] ch=new char[(int)sonFiles[0].length()];

        String text=null;

        try {

            Reader input=new FileReader(sonFiles[0]);

            input.read(ch);

            input.close();

            text=new String(ch).trim();

            return text;

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return text;

    }

    public void inputFile(File file) { //后续文件输入方法

        char[] ch=new char[(int)file.length()];

        try {

            Reader input=new FileReader(file);

            input.read(ch);

            input.close();

            this.textArea.setText(new String(ch).trim());

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    

    public void outputFile(String text) { //输出到文件方法

     if(!this.inOutFile.exists()) {

         try {

             this.inOutFile.createNewFile();

         } catch (IOException e) {

             // TODO Auto-generated catch block

             e.printStackTrace();

         }

     }

     try {

         Writer output=new FileWriter(this.inOutFile);

         output.write(text);

         output.close();

     } catch (IOException e) {

         // TODO Auto-generated catch block

         e.printStackTrace();

     }

     System.out.println("自动保存!");

     promptLabel();

    }

 

    public void promptLabel() { //提示标签 提示文件已自动保存

        JFrame frame=new JFrame();

        JLabel informationLabel=new JLabel("已自动保存");

        frame.add(informationLabel);

        

        informationLabel.setForeground(Color.BLACK);

        

        frame.setLocation(this.frame.getX()+200, this.frame.getY()+400);

        frame.setSize(150, 70);

        frame.setVisible(true);

        Thread t= new Thread(){

         public void run(){

             try {

                    Thread.sleep(3000);

                    informationLabel.setText("");

                    frame.dispose();

                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

         }

        };    

        t.start();

    }

    

    public void createTxt() { //新建文本

    JDialog frame=new JDialog(this.frame,"新建",true);

        JTextField txtName=new JTextField("");

        JPanel panel=new JPanel();

     JSplitPane splitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,txtName,panel);

     JButton yesButton=new JButton("YES");

     JLabel label=new JLabel("");

      

     yesButton.addActionListener(new ActionListener() {

            

            @Override

            public void actionPerformed(ActionEvent e) {

                if(e.getSource()==yesButton) {

                realizationCreateTxt(txtName, label);

                }

            }

        });

     txtName.addKeyListener(new KeyAdapter() {

         public void keyPressed(KeyEvent e) {

             if(e.getKeyCode()==KeyEvent.VK_ENTER) {

                 realizationCreateTxt(txtName, label);

             }

         }

        });

 

frame.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) {

        if(frameSum>1) frameSum--;

            }

        });    

    

     panel.setLayout(new FlowLayout(FlowLayout.CENTER));

        panel.add(yesButton);

        panel.add(label);

        frame.add(splitPane);

 

        splitPane.setDividerLocation(0.3);

        frame.setSize(300, 110);

        frame.setLocation(this.frame.getX()+200, this.frame.getY()+100);

        frame.setVisible(true);

}

    public void realizationCreateTxt(JTextField txtName,JLabel label) { //用方法实现替代多行代码操作

        StringBuffer name=new StringBuffer(parentsPath);

        name.append(File.separator+txtName.getText()).append(".txt");

     File file=new File(name.toString());

     if(!file.exists()) {

         try {

                file.createNewFile();

                this.fontSizeNum=20;

             this.fontColorNum="black";

             this.fontTypefaceNum="华文行楷";

             attributeSave();

                label.setText("创建成功");

            } catch (IOException e1) {

                e1.printStackTrace();

            }

     }else {

          label.setText("已有文件");

     }

     inOutFile=file;

     inputFile(inOutFile);

     attributeRead();

     changeStateLabel();

     frame.setTitle("记事本."+inOutFile.getName());

    }

    

    public File openNewFile() { //打开新文件

    JFileChooser fileChooser=new JFileChooser(Notepad.parentsPath);

    fileChooser.setDialogTitle("Open File");

    if(fileChooser.showOpenDialog(this.frame)==JFileChooser.APPROVE_OPTION) {

         this.inOutFile=fileChooser.getSelectedFile();

     }

    this.frameSum--;

    attributeRead();

    changeStateLabel();

    return this.inOutFile;

}

    

    public void saveFile() { //保存文件

        JFileChooser fileChooser=new JFileChooser(Notepad.parentsPath);

        fileChooser.setDialogTitle("Save File");

        if(fileChooser.showSaveDialog(this.frame)==JFileChooser.APPROVE_OPTION) {

            this.inOutFile=fileChooser.getSelectedFile();

            this.frame.setTitle("记事本."+inOutFile.getName());

            attributeSave();

        }

        this.frameSum--;

    }

    

    public void changeFontSize() { //改变字体大小

        JDialog frame=new JDialog(this.frame,"字体大小",true);

        JTextField fontsize=new JTextField("尺寸值(小于100)");

        JPanel panel=new JPanel();

     JSplitPane splitPane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,fontsize,panel);

     JButton yesButton=new JButton("YES");

     JLabel label=new JLabel("");

      

     fontsize.addMouseListener(new MouseAdapter() {

         @Override

         public void mouseEntered(MouseEvent e) {

             // TODO Auto-generated method stub

             mouseClicked(e);

         }

         @Override

         public void mouseClicked(MouseEvent e) {

             // TODO Auto-generated method stub

             if(e.getClickCount()==2) {

                 fontsize.setText("");

             }

         }

        });

      

     yesButton.addActionListener(new ActionListener() {

            

            @Override

            public void actionPerformed(ActionEvent e) {

                // TODO Auto-generated method stub

                if(e.getSource() instanceof JButton) {

                    if(e.getSource()==yesButton) {

                        realizationChangeFontSize(fontsize, label);

                    }

             }

            }

        });

     fontsize.addKeyListener(new KeyAdapter() {

         public void keyPressed(KeyEvent e) {

             if(e.getKeyCode()==KeyEvent.VK_ENTER) {

                 realizationChangeFontSize(fontsize, label);

             }

         }

        });

     frame.addWindowListener(new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

             frameSum--;

            }

        });

      

     panel.setLayout(new FlowLayout(FlowLayout.CENTER));

        panel.add(yesButton);

        panel.add(label);

        frame.add(splitPane);

    

        splitPane.setDividerLocation(0.3);

        frame.setSize(300, 110);

        frame.setLocation(this.frame.getX()+200, this.frame.getY()+100);

        frame.setVisible(true);

    }

    public void realizationChangeFontSize(JTextField fontsize,JLabel label) { //用方法实现替代多行代码操作

        try {

            this.fontSizeNum=Integer.parseInt(fontsize.getText());

            if(this.fontSizeNum>0&&this.fontSizeNum<=100) {

                this.textArea.setFont(new Font(this.fontTypefaceNum,this.fontStyle, this.fontSizeNum));

                changeStateLabel();

                attributeSave();

            }else {

                throw new Exception();

            }

            label.setText("尺寸正确,已修改");

        }catch(Exception e1) {

            label.setText("尺寸错误,请重试");

        }

    }

    

    public void changeColor() { //改变字体颜色

        JDialog frame=new JDialog(this.frame,"颜色选择",true);

        JPanel panel=new JPanel();

        JComboBox comboBox=new JComboBox(Notepad.colors);

        

        comboBox.setBorder(BorderFactory.createTitledBorder("您喜欢的颜色"));

        comboBox.setMaximumRowCount(4);

        

        comboBox.addItemListener(new ItemListener() {

            

            @Override

            public void itemStateChanged(ItemEvent e) {

                // TODO Auto-generated method stub

                if(e.getStateChange()==ItemEvent.SELECTED) {

                    fontColorNum=(String)e.getItem();

                    textArea.setForeground(judge(fontColorNum));

                    changeStateLabel();

                    attributeSave();

                }

            }

        });

        panel.add(comboBox);

        frame.add(panel);

        frame.addWindowListener(new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

             frameSum--;

            }

        });

        

        frame.setSize(250, 100);

        frame.setLocation(this.frame.getX()+200, this.frame.getY()+100);

        frame.setVisible(true);

        

    }

    public Color judge(String s) { //颜色匹配判断

        if("red".equalsIgnoreCase(s)) {

            return Color.RED;

        }else if("white".equalsIgnoreCase(s)) {

            return Color.WHITE;

        }else if("lightGray".equalsIgnoreCase(s)||"LIGHT_GRAY".equalsIgnoreCase(s)) {

            return Color.LIGHT_GRAY;

        }else if("gray".equalsIgnoreCase(s)) {

            return Color.GRAY;

        }else if("darkGray".equalsIgnoreCase(s)||"DARK_GRAY".equalsIgnoreCase(s)) {

            return Color.DARK_GRAY;

        }else if("black".equalsIgnoreCase(s)) {

            return Color.BLACK;

        }else if("pink".equalsIgnoreCase(s)) {

            return Color.PINK;

        }else if("orange".equalsIgnoreCase(s)) {

            return Color.ORANGE;

        }else if("yellow".equalsIgnoreCase(s)) {

            return Color.YELLOW;

        }else if("green".equalsIgnoreCase(s)) {

            return Color.GREEN;

        }else if("magenta".equalsIgnoreCase(s)) {

            return Color.MAGENTA;

        }else if("cyan".equalsIgnoreCase(s)) {

            return Color.CYAN;

        }else if("blue".equalsIgnoreCase(s)) {

            return Color.BLUE;

        } //"black","blue","cyan","darkGray","gray","green","lightGray","magenta","orange","pink","red","white";

        return null;

    }

      

public void changeFontTypeface() { //改变字体的字体

    JDialog frame=new JDialog(this.frame,"字体选择",true);

        JPanel panel=new JPanel();

        JComboBox comboBox=new JComboBox(Notepad.fonts);

        

        comboBox.setBorder(BorderFactory.createTitledBorder("想要的字体"));

        comboBox.setMaximumRowCount(8);

        comboBox.addItemListener(new ItemListener() {

            

            @Override

            public void itemStateChanged(ItemEvent e) {

                // TODO Auto-generated method stub

                if(e.getStateChange()==ItemEvent.SELECTED) {

                    fontTypefaceNum=(String)e.getItem();

                    textArea.setFont(new Font(fontTypefaceNum, fontStyle, fontSizeNum));

                    changeStateLabel();

                    attributeSave();

                }

            }

        });

        

        panel.add(comboBox);

        frame.add(panel);

        frame.addWindowListener(new WindowAdapter() {

            @Override

            public void windowClosing(WindowEvent e) {

             frameSum--;

            }

        });

        

        frame.setSize(250, 100);

        frame.setLocation(this.frame.getX()+200, this.frame.getY()+100);

        frame.setVisible(true);    

}

 

    public void printAllFont(String s[]) { //输出所有可用本机字体

        for(String str:s) {

            if(!Pattern.compile("[a-zA-Z]").matcher(String.valueOf(str.charAt(0))).matches()) { //正则表达式使用方法.只输出中文

                System.out.println(str);

            }

        }

    }

    

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        new Notepad();

    }

}

就是以上部分了。但是我没有用菜单面板,因为我是在教菜单面板之前就做好了,所以我用了选项卡面板,要是改的话也挺简单的,因为菜单面板和选项卡面板很像。但是最近比较忙,就不改了。

效果图:

 

 

posted @ 2019-11-29 14:29  李代璇  阅读(2308)  评论(2编辑  收藏  举报