0
点赞
收藏
分享

微信扫一扫

【JAVA】记事本

楠蛮鬼影 2022-03-17 阅读 171

仿照windows记事本,用JAVA语言编写的记事本软件。
实现对纯文本文件的新建、打开、保存、复制、粘贴、查找、替换等功能。
待实现但是失败了的功能:实时显示当前文本内的字数,实时显示时间。
可以对较大文件进行操作,有点慢)。
拿自己写的小说试了一下,姑且算是顺手吧!如果有当前字数就更好啦。
代码过长,一千多行,在这里放了部分,给大家提供参考,希望可以给大家提供一些帮助。

前期定义:

public class Text extends JFrame implements ActionListener,DocumentListener  
{   //菜单  
    JMenu fileMenu,editMenu,formatMenu,viewMenu,helpMenu;  
    //右键弹出菜单项  
    JPopupMenu popupMenu;  
    JMenuItem popupMenu_Undo,popupMenu_Cut,popupMenu_Copy,popupMenu_Paste,popupMenu_Delete,popupMenu_SelectAll;  
    //“文件”的菜单项  
    JMenuItem fileMenu_New,fileMenu_Open,fileMenu_Save,fileMenu_SaveAs,fileMenu_PageSetUp,fileMenu_Print,fileMenu_Exit;  
    //“编辑”的菜单项  
    JMenuItem editMenu_Undo,editMenu_Cut,editMenu_Copy,editMenu_Paste,editMenu_Delete,editMenu_Find,editMenu_FindNext,editMenu_Replace,editMenu_GoTo,editMenu_SelectAll,editMenu_TimeDate;  
    //“格式”的菜单项  
    JCheckBoxMenuItem formatMenu_LineWrap;  
    JMenuItem formatMenu_Font;  
    //“查看”的菜单项  
    JCheckBoxMenuItem viewMenu_Status;  
    //“帮助”的菜单项  
    JMenuItem helpMenu_HelpTopics,helpMenu_AboutNotepad;  
    //“文本”编辑区域  
    JTextArea editArea;  
    //状态栏标签  
    JLabel statusLabel;  
    //系统剪贴板  
    Toolkit toolkit=Toolkit.getDefaultToolkit();  
    Clipboard clipBoard=toolkit.getSystemClipboard();  
    //撤销  
    protected UndoManager undo=new UndoManager();  
    protected UndoableEditListener undoHandler=new UndoHandler();  
    //其他变量  
    String oldValue;//存放编辑区原来的内容,用于比较文本是否有改动  
    boolean isNewFile=true;//是否新文件(未保存过的)  
    File currentFile;//当前文件名  

菜单条-文件:

        JMenuBar menuBar=new JMenuBar();  
        //创建文件菜单及菜单项并注册事件监听  
        fileMenu=new JMenu("文件(F)");  
        fileMenu.setMnemonic('F');//设置快捷键ALT+F  
  
        fileMenu_New=new JMenuItem("新建(N)");  
        fileMenu_New.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));  
        fileMenu_New.addActionListener(this);  
  
        fileMenu_Open=new JMenuItem("打开(O)...");  
        fileMenu_Open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));  
        fileMenu_Open.addActionListener(this);  
  
        fileMenu_Save=new JMenuItem("保存(S)");  
        fileMenu_Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));  
        fileMenu_Save.addActionListener(this);  
  
        fileMenu_SaveAs=new JMenuItem("另存为(A)...");  
        fileMenu_SaveAs.addActionListener(this);  
  
        fileMenu_PageSetUp=new JMenuItem("页面设置(U)...");  
        fileMenu_PageSetUp.addActionListener(this);  
  
        fileMenu_Print=new JMenuItem("打印(P)...");  
        fileMenu_Print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));   
        fileMenu_Print.addActionListener(this);  
  
        fileMenu_Exit=new JMenuItem("退出(X)");  
        fileMenu_Exit.addActionListener(this);  
  
        editMenu=new JMenu("编辑(E)");  
        editMenu.setMnemonic('E');//设置快捷键ALT+E  
        
        editMenu.addMenuListener(new MenuListener()  
        {   public void menuCanceled(MenuEvent e)
            {   checkMenuItemEnabled();
            }  
            public void menuDeselected(MenuEvent e)
            {   checkMenuItemEnabled();
            }  
            public void menuSelected(MenuEvent e)
            {   checkMenuItemEnabled();
            }  
        });  
  
        editMenu_Undo=new JMenuItem("撤销(U)");  
        editMenu_Undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));  
        editMenu_Undo.addActionListener(this);  
        editMenu_Undo.setEnabled(false);  
  
        editMenu_Cut=new JMenuItem("剪切(T)");  
        editMenu_Cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));  
        editMenu_Cut.addActionListener(this);  
  
        editMenu_Copy=new JMenuItem("复制(C)");  
        editMenu_Copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));  
        editMenu_Copy.addActionListener(this);  
  
        editMenu_Paste=new JMenuItem("粘贴(P)");  
        editMenu_Paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));  
        editMenu_Paste.addActionListener(this);  
  
        editMenu_Delete=new JMenuItem("删除(D)");  
        editMenu_Delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));  
        editMenu_Delete.addActionListener(this);  
  
        editMenu_Find=new JMenuItem("查找(F)...");  
        editMenu_Find.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_MASK));  
        editMenu_Find.addActionListener(this);  
  
        editMenu_FindNext=new JMenuItem("查找下一个(N)");  
        editMenu_FindNext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));  
        editMenu_FindNext.addActionListener(this);  
  
        editMenu_Replace = new JMenuItem("替换(R)...",'R');   
        editMenu_Replace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK));   
        editMenu_Replace.addActionListener(this);  
  
        editMenu_GoTo = new JMenuItem("转到(G)...",'G');   
        editMenu_GoTo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK)); 
        editMenu_GoTo.addActionListener(this);  
  
        editMenu_SelectAll = new JMenuItem("全选",'A');   
        editMenu_SelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));   
        editMenu_SelectAll.addActionListener(this);  
  
        editMenu_TimeDate = new JMenuItem("时间/日期(D)",'D');  
        editMenu_TimeDate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));  
        editMenu_TimeDate.addActionListener(this);  
//设置菜单项的可用性:剪切,复制,粘帖,删除功能  
    public void checkMenuItemEnabled()  
    {   String selectText=editArea.getSelectedText();  
        if(selectText==null)  
        {   editMenu_Cut.setEnabled(false);  
            popupMenu_Cut.setEnabled(false);  
            editMenu_Copy.setEnabled(false);  
            popupMenu_Copy.setEnabled(false);  
            editMenu_Delete.setEnabled(false);  
            popupMenu_Delete.setEnabled(false);  
        }  
        else  
        {   editMenu_Cut.setEnabled(true);  
            popupMenu_Cut.setEnabled(true);   
            editMenu_Copy.setEnabled(true);  
            popupMenu_Copy.setEnabled(true);  
            editMenu_Delete.setEnabled(true);  
            popupMenu_Delete.setEnabled(true);  
        }  
        //粘帖功能可用性判断  
        Transferable contents=clipBoard.getContents(this);  
        if(contents==null)  
        {   editMenu_Paste.setEnabled(false);  
            popupMenu_Paste.setEnabled(false);  
        }  
        else  
        {   editMenu_Paste.setEnabled(true);  
            popupMenu_Paste.setEnabled(true);     
        }  
    }//方法checkMenuItemEnabled()结束  
  
    //关闭窗口时调用  
    public void exitWindowChoose()  
    {   editArea.requestFocus();  
        String currentValue=editArea.getText();  
        if(currentValue.equals(oldValue)==true)  
        {   System.exit(0);  
        }  
        else  
        {   int exitChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","退出提示",JOptionPane.YES_NO_CANCEL_OPTION);  
            if(exitChoose==JOptionPane.YES_OPTION)  
            {   //boolean isSave=false;  
                if(isNewFile)  
                {     
                    String str=null;  
                    JFileChooser fileChooser=new JFileChooser();  
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
                    fileChooser.setApproveButtonText("确定");  
                    fileChooser.setDialogTitle("另存为");  
                      
                    int result=fileChooser.showSaveDialog(this);  
                      
                    if(result==JFileChooser.CANCEL_OPTION)  
                    {   statusLabel.setText(" 您没有保存文件");  
                        return;  
                    }                     
      
                    File saveFileName=fileChooser.getSelectedFile();  
                  
                    if(saveFileName==null||saveFileName.getName().equals(""))  
                    {   JOptionPane.showMessageDialog(this,"不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE);  
                    }  
                    else   
                    {   try  
                        {   FileWriter fw=new FileWriter(saveFileName);  
                            BufferedWriter bfw=new BufferedWriter(fw);  
                            bfw.write(editArea.getText(),0,editArea.getText().length());  
                            bfw.flush();  
                            fw.close();  
                              
                            isNewFile=false;  
                            currentFile=saveFileName;  
                            oldValue=editArea.getText();  
                              
                            this.setTitle(saveFileName.getName()+"  - 记事本");  
                            statusLabel.setText(" 当前打开文件:"+saveFileName.getAbsoluteFile());  
                            //isSave=true;  
                        }                             
                        catch(IOException ioException){                   
                        }                 
                    }  
                }  
                else  
                {  
                    try  
                    {   FileWriter fw=new FileWriter(currentFile);  
                        BufferedWriter bfw=new BufferedWriter(fw);  
                        bfw.write(editArea.getText(),0,editArea.getText().length());  
                        bfw.flush();  
                        fw.close();  
                        //isSave=true;  
                    }                             
                    catch(IOException ioException){                   
                    }  
                }  
                System.exit(0);  
             
            }  
            else if(exitChoose==JOptionPane.NO_OPTION)  
            {   System.exit(0);  
            }  
            else  
            {   return;  
            }  
        }  
    }//关闭窗口时调用方法结束  
  
    //查找方法  
    public void find()  
    {   final JDialog findDialog=new JDialog(this,"查找",false); 
        Container con=findDialog.getContentPane();
        con.setLayout(new FlowLayout(FlowLayout.LEFT));  
        JLabel findContentLabel=new JLabel("查找内容(N):");  
        final JTextField findText=new JTextField(15);  
        JButton findNextButton=new JButton("查找下一个(F):");  
        final JCheckBox matchCheckBox=new JCheckBox("区分大小写(C)");  
        ButtonGroup bGroup=new ButtonGroup();  
        final JRadioButton upButton=new JRadioButton("向上(U)");  
        final JRadioButton downButton=new JRadioButton("向下(U)");  
        
        downButton.setSelected(true);  
        bGroup.add(upButton);  
        bGroup.add(downButton); 
        JButton cancel=new JButton("取消");  
        
        //取消按钮事件处理  
        cancel.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   findDialog.dispose();  
            }  
        });  
        //"查找下一个"按钮监听  
        findNextButton.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   //"区分大小写(C)"的JCheckBox是否被选中  
                int k=0,m=0;  
                final String str1,str2,str3,str4,strA,strB;  
                str1=editArea.getText();  
                str2=findText.getText();  
                str3=str1.toUpperCase();  
                str4=str2.toUpperCase();  
                if(matchCheckBox.isSelected())//区分大小写  
                {   strA=str1;  
                    strB=str2;  
                }  
                else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找   
                {   strA=str3;  
                    strB=str4;  
                }  
                if(upButton.isSelected())  
                {   //k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
                    if(editArea.getSelectedText()==null)  
                        k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
                    else  
                        k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1);      
                    if(k>-1)  
                    {   //String strData=strA.subString(k,strB.getText().length()+1);  
                        editArea.setCaretPosition(k);  
                        editArea.select(k,k+strB.length());  
                    }  
                    else  
                    {   JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
                    }  
                }  
                else if(downButton.isSelected())  
                {   if(editArea.getSelectedText()==null)  
                        k=strA.indexOf(strB,editArea.getCaretPosition()+1);  
                    else  
                        k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1);      
                    if(k>-1)  
                    {   //String strData=strA.subString(k,strB.getText().length()+1);  
                        editArea.setCaretPosition(k);  
                        editArea.select(k,k+strB.length());  
                    }  
                    else  
                    {   JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
                    }  
                }  
            }  
        });//"查找下一个"按钮监听结束  
        //创建"查找"对话框的界面  
        JPanel panel1=new JPanel();  
        JPanel panel2=new JPanel();  
        JPanel panel3=new JPanel();  
        JPanel directionPanel=new JPanel();  
        
        directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));  
        directionPanel.add(upButton);  
        directionPanel.add(downButton);  
        
        panel1.setLayout(new GridLayout(2,1));  
        panel1.add(findNextButton);  
        panel1.add(cancel);  
        panel2.add(findContentLabel);  
        panel2.add(findText);  
        panel2.add(panel1);  
        panel3.add(matchCheckBox);  
        panel3.add(directionPanel);  
        con.add(panel2);  
        con.add(panel3);  
        findDialog.setSize(410,180);  
        findDialog.setResizable(false);//不可调整大小  
        findDialog.setLocation(230,280);  
        findDialog.setVisible(true);  
    }//查找方法结束  
      
    //替换方法  
    public void replace()  
    {   final JDialog replaceDialog=new JDialog(this,"替换",false);//false时允许其他窗口同时处于激活状态(即无模式)  
        Container con=replaceDialog.getContentPane();//返回此对话框的contentPane对象  
        con.setLayout(new FlowLayout(FlowLayout.CENTER));  
        JLabel findContentLabel=new JLabel("查找内容(N):");  
        final JTextField findText=new JTextField(15);  
        JButton findNextButton=new JButton("查找下一个(F):");  
        JLabel replaceLabel=new JLabel("替换为(P):");  
        final JTextField replaceText=new JTextField(15);  
        JButton replaceButton=new JButton("替换(R)");  
        JButton replaceAllButton=new JButton("全部替换(A)");  
        JButton cancel=new JButton("取消");  
        cancel.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   replaceDialog.dispose();  
            }  
        });  
        final JCheckBox matchCheckBox=new JCheckBox("区分大小写(C)");  
        ButtonGroup bGroup=new ButtonGroup();  
        final JRadioButton upButton=new JRadioButton("向上(U)");  
        final JRadioButton downButton=new JRadioButton("向下(U)");  
        downButton.setSelected(true);  
        bGroup.add(upButton);  
        bGroup.add(downButton);  

          
        //"查找下一个"按钮监听  
        findNextButton.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   
                int k=0,m=0;  
                final String str1,str2,str3,str4,strA,strB;  
                str1=editArea.getText();  
                str2=findText.getText();  
                str3=str1.toUpperCase();  
                str4=str2.toUpperCase();  
                if(matchCheckBox.isSelected())//区分大小写  
                {   strA=str1;  
                    strB=str2;  
                }  
                else
                {   strA=str3;  
                    strB=str4;  
                }  
                if(upButton.isSelected())  
                {   
                    if(editArea.getSelectedText()==null)  
                        k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
                    else  
                        k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1);      
                    if(k>-1)  
                    {   //String strData=strA.subString(k,strB.getText().length()+1);  
                        editArea.setCaretPosition(k);  
                        editArea.select(k,k+strB.length());  
                    }  
                    else  
                    {   JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
                    }  
                }  
                else if(downButton.isSelected())  
                {   if(editArea.getSelectedText()==null)  
                        k=strA.indexOf(strB,editArea.getCaretPosition()+1);  
                    else  
                        k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1);      
                    if(k>-1)  
                    {   //String strData=strA.subString(k,strB.getText().length()+1);  
                        editArea.setCaretPosition(k);  
                        editArea.select(k,k+strB.length());  
                    }  
                    else  
                    {   JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
                    }  
                }  
            }  
        });//"查找下一个"按钮监听结束  
          
        //"替换"按钮监听  
        replaceButton.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   if(replaceText.getText().length()==0 && editArea.getSelectedText()!=null)   
                    editArea.replaceSelection("");   
                if(replaceText.getText().length()>0 && editArea.getSelectedText()!=null)   
                    editArea.replaceSelection(replaceText.getText());  
            }  
        });//"替换"按钮监听结束  
          
        //"全部替换"按钮监听  
        replaceAllButton.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   editArea.setCaretPosition(0);   //将光标放到编辑区开头      
                int k=0,m=0,replaceCount=0;  
                if(findText.getText().length()==0)  
                {   JOptionPane.showMessageDialog(replaceDialog,"请填写查找内容!","提示",JOptionPane.WARNING_MESSAGE);  
                    findText.requestFocus(true);  
                    return;  
                }  
                while(k>-1)//当文本中有内容被选中时(k>-1被选中)进行替换,否则不进行while循环  
                {   //"区分大小写(C)"的JCheckBox是否被选中  
                    //int k=0,m=0;  
                    final String str1,str2,str3,str4,strA,strB;  
                    str1=editArea.getText();  
                    str2=findText.getText();  
                    str3=str1.toUpperCase();  
                    str4=str2.toUpperCase();  
                    if(matchCheckBox.isSelected())//区分大小写  
                    {   strA=str1;  
                        strB=str2;  
                    }  
                    else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找   
                    {   strA=str3;  
                        strB=str4;  
                    }  
                    if(upButton.isSelected())  
                    {   //k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
                        if(editArea.getSelectedText()==null)  
                            k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
                        else  
                            k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1);      
                        if(k>-1)  
                        {   //String strData=strA.subString(k,strB.getText().length()+1);  
                            editArea.setCaretPosition(k);  
                            editArea.select(k,k+strB.length());  
                        }  
                        else  
                        {   if(replaceCount==0)  
                            {   JOptionPane.showMessageDialog(replaceDialog, "找不到您查找的内容!", "记事本",JOptionPane.INFORMATION_MESSAGE);   
                            }  
                            else  
                            {   JOptionPane.showMessageDialog(replaceDialog,"成功替换"+replaceCount+"个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE);  
                            }  
                        }  
                    }  
                    else if(downButton.isSelected())  
                    {   if(editArea.getSelectedText()==null)  
                            k=strA.indexOf(strB,editArea.getCaretPosition()+1);  
                        else  
                            k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1);      
                        if(k>-1)  
                        {   //String strData=strA.subString(k,strB.getText().length()+1);  
                            editArea.setCaretPosition(k);  
                            editArea.select(k,k+strB.length());  
                        }  
                        else  
                        {   if(replaceCount==0)  
                            {   JOptionPane.showMessageDialog(replaceDialog, "找不到您查找的内容!", "记事本",JOptionPane.INFORMATION_MESSAGE);   
                            }  
                            else  
                            {   JOptionPane.showMessageDialog(replaceDialog,"成功替换"+replaceCount+"个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE);  
                            }  
                        }  
                    }  
                    if(replaceText.getText().length()==0 && editArea.getSelectedText()!= null)  
                    {   editArea.replaceSelection("");  
                        replaceCount++;  
                    }   
                      
                    if(replaceText.getText().length()>0 && editArea.getSelectedText()!= null)   
                    {   editArea.replaceSelection(replaceText.getText());   
                        replaceCount++;  
                    }  
                }//while循环结束  
            }  
        });//"替换全部"方法结束  
          
        //创建"替换"对话框的界面  
        JPanel directionPanel=new JPanel();  
        directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));  
  
        directionPanel.add(downButton);  
        JPanel panel1=new JPanel();  
        JPanel panel2=new JPanel();  
        JPanel panel3=new JPanel();  
        JPanel panel4=new JPanel();  
        panel4.setLayout(new GridLayout(2,1));  
        panel1.add(findContentLabel);  
        panel1.add(findText);  
        panel1.add(findNextButton);  
        panel4.add(replaceButton);  
        panel4.add(replaceAllButton);  
        panel2.add(replaceLabel);  
        panel2.add(replaceText);  
        panel2.add(panel4);  
        panel3.add(matchCheckBox);  
        panel3.add(directionPanel);  
        panel3.add(cancel);  
        con.add(panel1);  
        con.add(panel2);  
        con.add(panel3);  
        replaceDialog.setSize(420,220);  
        replaceDialog.setResizable(false);
        replaceDialog.setLocation(230,280);  
        replaceDialog.setVisible(true);  
    }
    public void font()  
    {   final JDialog fontDialog=new JDialog(this,"字体设置",false);  
        Container con=fontDialog.getContentPane();  
        con.setLayout(new FlowLayout(FlowLayout.LEFT));  
        JLabel fontLabel=new JLabel("字体(F):");  
        fontLabel.setPreferredSize(new Dimension(100,20));
        JLabel styleLabel=new JLabel("字形(Y):");  
        styleLabel.setPreferredSize(new Dimension(100,20));  
        JLabel sizeLabel=new JLabel("大小(S):");  
        sizeLabel.setPreferredSize(new Dimension(100,20));  
        final JLabel sample=new JLabel("BB亲的记事本-MCC's Notepad");  
        //sample.setHorizontalAlignment(SwingConstants.CENTER);  
        final JTextField fontText=new JTextField(9);  
        fontText.setPreferredSize(new Dimension(200,20));  
        final JTextField styleText=new JTextField(8);  
        styleText.setPreferredSize(new Dimension(200,20));  
        final int style[]={Font.PLAIN,Font.BOLD,Font.ITALIC,Font.BOLD+Font.ITALIC};  
        final JTextField sizeText=new JTextField(5);  
        sizeText.setPreferredSize(new Dimension(200,20));  
        JButton okButton=new JButton("确定");  
        JButton cancel=new JButton("取消");  
        cancel.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   fontDialog.dispose();     
            }  
        });  
        Font currentFont=editArea.getFont();  
        fontText.setText(currentFont.getFontName());  
        fontText.selectAll();  
        //styleText.setText(currentFont.getStyle());  
        //styleText.selectAll();  
        if(currentFont.getStyle()==Font.PLAIN)  
            styleText.setText("常规");  
        else if(currentFont.getStyle()==Font.BOLD)  
            styleText.setText("粗体");  
        else if(currentFont.getStyle()==Font.ITALIC)  
            styleText.setText("斜体");  
        else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))  
            styleText.setText("粗斜体");  
        styleText.selectAll();  
        String str=String.valueOf(currentFont.getSize());  
        sizeText.setText(str);  
        sizeText.selectAll();  
        final JList fontList,styleList,sizeList;  
        GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();  
        final String fontName[]=ge.getAvailableFontFamilyNames();  
        fontList=new JList(fontName);  
        fontList.setFixedCellWidth(86);  
        fontList.setFixedCellHeight(20);  
        fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
        final String fontStyle[]={"常规","粗体","斜体","粗斜体"};  
        styleList=new JList(fontStyle);  
        styleList.setFixedCellWidth(86);  
        styleList.setFixedCellHeight(20);  
        styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
        if(currentFont.getStyle()==Font.PLAIN)  
            styleList.setSelectedIndex(0);  
        else if(currentFont.getStyle()==Font.BOLD)  
            styleList.setSelectedIndex(1);  
        else if(currentFont.getStyle()==Font.ITALIC)  
            styleList.setSelectedIndex(2);  
        else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))  
            styleList.setSelectedIndex(3);  
        final String fontSize[]={"8","9","10","11","12","14","16","18","20","22","24","26","28","36","48","72"};  
        sizeList=new JList(fontSize);  
        sizeList.setFixedCellWidth(43);  
        sizeList.setFixedCellHeight(20);  
        sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
        fontList.addListSelectionListener(new ListSelectionListener()  
        {   public void valueChanged(ListSelectionEvent event)  
            {   fontText.setText(fontName[fontList.getSelectedIndex()]);  
                fontText.selectAll();  
                Font sampleFont1=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));  
                sample.setFont(sampleFont1);  
            }  
        });  
        styleList.addListSelectionListener(new ListSelectionListener()  
        {   public void valueChanged(ListSelectionEvent event)  
            {   int s=style[styleList.getSelectedIndex()];  
                styleText.setText(fontStyle[s]);  
                styleText.selectAll();  
                Font sampleFont2=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));  
                sample.setFont(sampleFont2);  
            }  
        });  
        sizeList.addListSelectionListener(new ListSelectionListener()  
        {   public void valueChanged(ListSelectionEvent event)  
            {   sizeText.setText(fontSize[sizeList.getSelectedIndex()]);  
                //sizeText.requestFocus();  
                sizeText.selectAll();     
                Font sampleFont3=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));  
                sample.setFont(sampleFont3);  
            }  
        });  
        okButton.addActionListener(new ActionListener()  
        {   public void actionPerformed(ActionEvent e)  
            {   Font okFont=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));  
                editArea.setFont(okFont);  
                fontDialog.dispose();  
            }  
        });  
        JPanel samplePanel=new JPanel();  
        samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));  
 
        samplePanel.add(sample);  
        JPanel panel1=new JPanel();  
        JPanel panel2=new JPanel();  
        JPanel panel3=new JPanel();  
        panel2.add(fontText);  
        panel2.add(styleText);  
        panel2.add(sizeText);  
        panel2.add(okButton);  
        panel3.add(new JScrollPane(fontList));
        panel3.add(new JScrollPane(styleList));  
        panel3.add(new JScrollPane(sizeList));  
        panel3.add(cancel);  
        con.add(panel1);  
        con.add(panel2);  
        con.add(panel3);  
        con.add(samplePanel);  
        fontDialog.setSize(350,340);  
        fontDialog.setLocation(200,200);  
        fontDialog.setResizable(false);  
        fontDialog.setVisible(true);  
    }  
  
    public void actionPerformed(ActionEvent e)  
    {   //新建  
        if(e.getSource()==fileMenu_New)  
        {   editArea.requestFocus();  
            String currentValue=editArea.getText();  
            boolean isTextChange=(currentValue.equals(oldValue))?false:true;  
            if(isTextChange)  
            {   int saveChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","提示",JOptionPane.YES_NO_CANCEL_OPTION);  
                if(saveChoose==JOptionPane.YES_OPTION)  
                {   String str=null;  
                    JFileChooser fileChooser=new JFileChooser();  
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
                    //fileChooser.setApproveButtonText("确定");  
                    fileChooser.setDialogTitle("另存为");  
                    int result=fileChooser.showSaveDialog(this);  
                    if(result==JFileChooser.CANCEL_OPTION)  
                    {   statusLabel.setText("您没有选择任何文件");  
                        return;  
                    }  
                    File saveFileName=fileChooser.getSelectedFile();  
                    if(saveFileName==null || saveFileName.getName().equals(""))  
                    {   JOptionPane.showMessageDialog(this,"不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE);  
                    }  
                    else   
                    {   try  
                        {   FileWriter fw=new FileWriter(saveFileName);  
                            BufferedWriter bfw=new BufferedWriter(fw);  
                            bfw.write(editArea.getText(),0,editArea.getText().length());  
                            bfw.flush();//刷新该流的缓冲  
                            bfw.close();  
                            isNewFile=false;  
                            currentFile=saveFileName;  
                            oldValue=editArea.getText();  
                            this.setTitle(saveFileName.getName()+" - 记事本");  
                            statusLabel.setText("当前打开文件:"+saveFileName.getAbsoluteFile());  
                        }  
                        catch (IOException ioException)  
                        {  
                        }  
                    }  
                }  
                else if(saveChoose==JOptionPane.NO_OPTION)  
                {   editArea.replaceRange("",0,editArea.getText().length());  
                    statusLabel.setText(" 新建文件");  
                    this.setTitle("无标题 - 记事本");  
                    isNewFile=true;  
                    undo.discardAllEdits(); //撤消所有的"撤消"操作  
                    editMenu_Undo.setEnabled(false);  
                    oldValue=editArea.getText();  
                }  
                else if(saveChoose==JOptionPane.CANCEL_OPTION)  
                {   return;  
                }  
            }  
            else  
            {   editArea.replaceRange("",0,editArea.getText().length());  
                statusLabel.setText(" 新建文件");  
                this.setTitle("无标题 - 记事本");  
                isNewFile=true;  
                undo.discardAllEdits();//撤消所有的"撤消"操作  
                editMenu_Undo.setEnabled(false);  
                oldValue=editArea.getText();  
            }  
        }//新建结束  
        
举报

相关推荐

0 条评论