記事本代碼


記事本代碼

如下:

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();

    }

}

就是以上部分了。但是我沒有用菜單面板,因為我是在教菜單面板之前就做好了,所以我用了選項卡面板,要是改的話也挺簡單的,因為菜單面板和選項卡面板很像。但是最近比較忙,就不改了。

效果圖:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM