0
点赞
收藏
分享

微信扫一扫

自己做的java 记事本(查找,替换部分功能缺失) 多多交流

倚然君 2023-06-01 阅读 72

import javax.swing.*;
 import javax.swing.event.UndoableEditListener;
 import javax.swing.undo.CannotUndoException;
 import javax.swing.undo.UndoManager;
 import java.io.*;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.GregorianCalendar;
 import java.awt.*;
 import java.awt.datatransfer.Clipboard;
 import java.awt.datatransfer.DataFlavor;
 import java.awt.datatransfer.StringSelection;
 import java.awt.datatransfer.Transferable;
 import java.awt.event.*;
 public  class TextbookTest extends JFrame implements ActionListener,ItemListener
 {
 //申明组件*********************************************************
  //********************菜单跟菜单项**********
  JMenuBar menubar;//菜单条
  JMenu menu_file,menu_edit,menu_format,menu_look,menu_help;//菜单
  JMenuItem file_open,file_save,file_new,file_asave,file_quit,file_print;//文件菜单项
  JMenuItem edit_cut,edit_copy,edit_paste,edit_del,edit_undo,edit_find,edit_findnext,edit_replace,eidt_goto,edit_selectall,edit_date;//编辑菜单项
  JMenuItem format_fcolor,format_bcolor,format_bold;//格式菜单项
  //查看菜单项
  JCheckBoxMenuItem format_linewrap,look_state;
  JMenuItem help_help,help_about;//帮助菜单项
  //************文本区
  JTextArea area;//文本区
  
  //****************************工具栏
  Icon newIcon ,openIcon ,saveAsIcon ,printIcon ,undoIcon ;
  Icon  cutIcon ,copyIcon ,pasteIcon ,deleteIcon,searchIcon;
  Icon timeIcon ,fontIcon,boldIcon,italicIcon,bgcolorIcon;
  Icon fgcolorIcon,helpIcon,saveIcon;
   JButton newButton ,openButton,saveButton,saveAsButton ,printButton ,undoButton;
  JButton cutButton ,copyButton, pasteButton,deleteButton ,searchButton,timeButton;
   
  JButton fontButton ,boldButton,italicButton,fgcolorButton,bgcolorButton ,helpButton ;
 //*****************浮动菜单***************
    JToolBar  statusBar ;  
   JLabel statusLabel1 ,statusLabel2 ,statusLabel3; 
   //******************************浮动菜单**********
   JPopupMenu popupMenu;
   JMenuItem popupMenu_Undo,popupMenu_Cut ,popupMenu_Copy,popupMenu_Paste,popupMenu_Delete,popupMenu_SelectAll;
  
 //*************************撤销管理器**************
   protected UndoManager undo = new UndoManager();
 //  protected UndoableEditListener undoHandler = new UndoHandler();
   Clipboard clipboard;
   //*************************时间日期**************
   GregorianCalendar time = new GregorianCalendar();
   int hour = time.get(Calendar.HOUR_OF_DAY);
   int min = time.get(Calendar.MINUTE);
   int second = time.get(Calendar.SECOND);
   //************字体*******************
   JComboBox box_font,box_style,box_size;
      String name="宋体";
   int size=20;
   int style=0;
   Font f=null;
  //*******************构造函数********************************
  TextbookTest(String s)
  {  
   super(s);
   //************菜单
   menubar=new JMenuBar();
   menu_file=new JMenu("文件(F)",true);
   menu_edit=new JMenu("编辑(E)",true);
       menu_format=new JMenu("格式(O)",true);
        menu_look=new JMenu("查看(V)",true);
       menu_help=new JMenu("帮助(H)",true);
       menu_file.setMnemonic('f');
       menu_edit.setMnemonic('e');
       menu_format.setMnemonic('o');
        menu_look.setMnemonic('v');
       menu_help.setMnemonic('h');
       menubar.add(menu_file);
       menubar.add(menu_edit);
       menubar.add(menu_format);
       menubar.add(menu_look);
       menubar.add(menu_help);
       //********菜单项*************
       file_open=new JMenuItem("打开");
          file_save=new JMenuItem("保存");
          file_new=new JMenuItem("新建");
           file_asave=new JMenuItem("另存为");
           file_quit=new JMenuItem("退出");
          file_print=new JMenuItem("打印");//文件菜单项
     edit_cut=new JMenuItem("剪切");
            edit_copy=new JMenuItem("复制");
           edit_paste=new JMenuItem("粘贴");
           edit_del=new JMenuItem("删除");
           edit_undo=new JMenuItem("撤销");
          edit_find=new JMenuItem("查找");
           edit_findnext=new JMenuItem("查找下一处");
              edit_replace=new JMenuItem("替换");
             eidt_goto=new JMenuItem("转到");
            edit_selectall=new JMenuItem("全选");
              edit_date=new JMenuItem("日期");//编辑菜单项
  format_linewrap=new JCheckBoxMenuItem("自动换行");
           
 JMenu format_color=new JMenu("颜色");
 format_fcolor=new JMenuItem("字体颜色");
 format_bcolor=new JMenuItem("背景颜色");
 format_color.add(format_fcolor);
 format_color.add(format_bcolor);
  
         format_bold=new JMenuItem("字体");//格式菜单项
      look_state=new JCheckBoxMenuItem("状态");//查看菜单项
    help_help=new JMenuItem("帮助");
           help_about=new JMenuItem("关于");//帮助菜单项
           file_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
         file_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
           file_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
            file_asave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,InputEvent.CTRL_MASK));
            file_quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
           file_print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));
      edit_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));
             edit_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));
            edit_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));
            edit_del.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
            edit_undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));
           edit_find.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_MASK));
            edit_findnext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
               edit_replace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,InputEvent.CTRL_MASK));
              eidt_goto.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,InputEvent.CTRL_MASK));
             edit_selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
               edit_date.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));
               
           menu_file.add(file_open);
           menu_file.add(file_save);
           menu_file.add(file_asave);
           menu_file.addSeparator();
           menu_file.add(file_print);
           menu_file.addSeparator();
           menu_file.add(file_quit);
            menu_edit.add(edit_undo);
            menu_edit.add(edit_cut);
           menu_edit.add(edit_copy);
           menu_edit.add(edit_paste);
           menu_edit.add(edit_del);
          menu_edit.addSeparator();
           menu_edit.add(edit_find);
           menu_edit.add(edit_findnext);
           menu_edit.add(edit_replace);
           menu_edit.add(eidt_goto);
           menu_edit.addSeparator();
           menu_edit.add(edit_selectall);
           menu_edit.add(edit_date);
           menu_format.add(format_linewrap);
           menu_format.addSeparator();
           menu_format.add(format_color);
           menu_format.add(format_bold);
           menu_look.add(look_state);
           menu_help.add(help_help);
           menu_help.addSeparator();
           menu_help.add(help_about);
           
           
           file_open.addActionListener(this);
           file_save.addActionListener(this);
           file_new.addActionListener(this);
            file_asave.addActionListener(this);
            file_quit.addActionListener(this);
           file_print.addActionListener(this);
      edit_cut.addActionListener(this);
             edit_copy.addActionListener(this);
            edit_paste.addActionListener(this);
            edit_del.addActionListener(this);
            edit_undo.addActionListener(this);
           edit_find.addActionListener(this);
            edit_findnext.addActionListener(this);
               edit_replace.addActionListener(this);
              eidt_goto.addActionListener(this);
             edit_selectall.addActionListener(this);
               edit_date.addActionListener(this);
               format_linewrap.addActionListener(this);
               format_fcolor.addActionListener(this);
               format_bcolor.addActionListener(this);
          format_bold.addActionListener(this);
       look_state.addActionListener(this);
     help_help.addActionListener(this);
            help_about.addActionListener(this);
            this.setJMenuBar(menubar);
           //****************内容面板***********
            Container con=getContentPane();
           area=new JTextArea(10,10);
           area.requestFocus();
           //********文本区*********************
           JScrollPane pane=new JScrollPane(area);
           pane.setRequestFocusEnabled(true);
           con.add(pane);
           con.setVisible(true);
        
        //*************************状态栏***************
           statusBar = new JToolBar();
     statusBar.setLayout(new FlowLayout(FlowLayout.LEFT));
      statusLabel1 = new JLabel("开发者:李福春               ");
      statusLabel2 = new JLabel(" 当前时间:"+hour+":"+min+" "+second);
      statusLabel3 = new JLabel(" 当前光标所在行数" /*+ getlineNumber()*/);
     statusBar.add(statusLabel1);
     statusBar.addSeparator();
     statusBar.add(statusLabel2);
     statusBar.addSeparator();
     statusBar.add(statusLabel3);
     con.add(statusBar, BorderLayout.SOUTH);
     statusBar.setVisible(false);
     
     
     //***************************字体控制
      box_font=new JComboBox();
        box_style=new JComboBox();
        box_size=new JComboBox();
     GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
     String fontName[]=ge.getAvailableFontFamilyNames();
     for(int i=0;i<fontName.length;i++)
     {
      box_font.addItem(fontName[i]);
     }
     box_font.addItemListener(this);
     int font_size[]=new int[20];
     for(int j=10,i=1;j<=80;j+=2,i++)
     {
      
       box_size.addItem(j);  
     }
     box_size.addItemListener(this);
     box_style.addItem("加粗");
     box_style.addItem("斜体");
     box_style.addItem("常规");
     box_style.addItem("粗斜体");
     box_style.addItemListener(this);
     box_font.setSelectedItem("宋体");
     box_style.setSelectedIndex(2);
     box_size.setSelectedIndex(10);
     //*************************工具栏*********************
     JPanel toolBar = new JPanel();
   toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));  newIcon = new ImageIcon("Icons/new.gif");
   openIcon = new ImageIcon("Icons/open.gif");
    saveIcon = new ImageIcon("Icons/save.gif");
    saveAsIcon = new ImageIcon("Icons/saveas.gif");
    printIcon = new ImageIcon("Icons/print.gif");
    undoIcon = new ImageIcon("Icons/undo.gif");
   cutIcon = new ImageIcon("Icons/cut.gif");
   copyIcon = new ImageIcon("Icons/copy.gif");
   pasteIcon = new ImageIcon("Icons/paste.gif");
    deleteIcon = new ImageIcon("Icons/delete.gif");
    searchIcon = new ImageIcon("Icons/search.gif");
    timeIcon = new ImageIcon("Icons/time.gif");
    fontIcon = new ImageIcon("Icons/font.gif");
    boldIcon = new ImageIcon("Icons/bold.gif");
    italicIcon = new ImageIcon("Icons/italic.gif");
    bgcolorIcon = new ImageIcon("Icons/bgcolor.gif");
    fgcolorIcon = new ImageIcon("Icons/fgcolor.gif");
    helpIcon = new ImageIcon("Icons/help.gif");   newButton = new JButton(newIcon);
    openButton = new JButton(openIcon);
    saveButton = new JButton(saveIcon);
    saveAsButton = new JButton(saveAsIcon);
    printButton = new JButton(printIcon);
    undoButton = new JButton(undoIcon);
 //  undoButton.setEnabled(false);
    cutButton = new JButton(cutIcon);
 //   cutButton.setEnabled(false);
    copyButton = new JButton(copyIcon);
 //   copyButton.setEnabled(false);
    JButton pasteButton = new JButton(pasteIcon);
 //  pasteButton.setEnabled(false);
    deleteButton = new JButton(deleteIcon);
 //  deleteButton.setEnabled(false);
    searchButton = new JButton(searchIcon);
    timeButton = new JButton(timeIcon);
    fontButton = new JButton(fontIcon);
    boldButton = new JButton(boldIcon);
    italicButton = new JButton(italicIcon);
    fgcolorButton = new JButton(fgcolorIcon);
    bgcolorButton = new JButton(bgcolorIcon);
   helpButton = new JButton(helpIcon);
         box_font.setPreferredSize(new Dimension(60, 22)); 
         box_size.setPreferredSize(new Dimension(60, 22));  
         box_style.setPreferredSize(new Dimension(60, 22));  
   newButton.setPreferredSize(new Dimension(22, 22));
   openButton.setPreferredSize(new Dimension(22, 22));
   saveButton.setPreferredSize(new Dimension(22, 22));
   saveAsButton.setPreferredSize(new Dimension(22, 22));
   printButton.setPreferredSize(new Dimension(22, 22));
   undoButton.setPreferredSize(new Dimension(22, 22));
   cutButton.setPreferredSize(new Dimension(22, 22));
   copyButton.setPreferredSize(new Dimension(22, 22));
   pasteButton.setPreferredSize(new Dimension(22, 22));
   deleteButton.setPreferredSize(new Dimension(22, 22));
   searchButton.setPreferredSize(new Dimension(22, 22));
   timeButton.setPreferredSize(new Dimension(22, 22));
 //  fontButton.setPreferredSize(new Dimension(22, 22));
 //  boldButton.setPreferredSize(new Dimension(22, 22));
   italicButton.setPreferredSize(new Dimension(22, 22));
   fgcolorButton.setPreferredSize(new Dimension(22, 22));
   bgcolorButton.setPreferredSize(new Dimension(22, 22));
   helpButton.setPreferredSize(new Dimension(22, 22));
   // -----------------------------------注册工具栏按钮事件
   newButton.addActionListener(this);
   openButton.addActionListener(this);
   saveButton.addActionListener(this);
   saveAsButton.addActionListener(this);
   printButton.addActionListener(this);
   undoButton.addActionListener(this);
   cutButton.addActionListener(this);
   copyButton.addActionListener(this);
   pasteButton.addActionListener(this);
   deleteButton.addActionListener(this);
   searchButton.addActionListener(this);
   timeButton.addActionListener(this);
   fontButton.addActionListener(this);
   boldButton.addActionListener(this);
   italicButton.addActionListener(this);
   fgcolorButton.addActionListener(this);
   bgcolorButton.addActionListener(this);
   helpButton.addActionListener(this);
   // ------------------------设置按钮提示文字
   newButton.setToolTipText("新建");
   openButton.setToolTipText("打开");
   saveButton.setToolTipText("保存");
   saveAsButton.setToolTipText("另存为");
   printButton.setToolTipText("打印");
   undoButton.setToolTipText("撤消");
   cutButton.setToolTipText("剪切");
   copyButton.setToolTipText("复制");
   pasteButton.setToolTipText("粘贴");
   deleteButton.setToolTipText("删除所选");
   searchButton.setToolTipText("查找与替换");
   timeButton.setToolTipText("插入时间/日期");
 //  fontButton.setToolTipText("设置字体");
 //  boldButton.setToolTipText("粗体");
   box_font.setToolTipText("设置字体");
   box_size.setToolTipText("设置字号");
   box_style.setToolTipText("设置字型");
   italicButton.setToolTipText("斜体");
   fgcolorButton.setToolTipText("设置字体颜色");
   bgcolorButton.setToolTipText("设置背景颜色");
   helpButton.setToolTipText("帮助");
   // 设置撤消、重做、剪切、复制、粘贴、删除等工具栏按钮不可用时的图片(灰色)
   undoButton.setDisabledIcon(new ImageIcon("Icons/undo1.gif"));
   cutButton.setDisabledIcon(new ImageIcon("Icons/cut1.gif"));
   copyButton.setDisabledIcon(new ImageIcon("Icons/copy1.gif"));
   pasteButton.setDisabledIcon(new ImageIcon("Icons/paste1.gif"));
   deleteButton.setDisabledIcon(new ImageIcon("Icons/delete1.gif"));
   // ------------------------向工具栏添加按钮
   
   toolBar.add(newButton);
   toolBar.add(openButton);
   toolBar.add(saveButton);
   toolBar.add(saveAsButton);
   toolBar.add(printButton);
   toolBar.add(undoButton);
   toolBar.add(cutButton);
   toolBar.add(copyButton);
   toolBar.add(pasteButton);
   toolBar.add(deleteButton);
   toolBar.add(searchButton);
   toolBar.add(timeButton);
 //  toolBar.add(fontButton);
 //  toolBar.add(boldButton);
   
 //  toolBar.add(italicButton);
   toolBar.add(fgcolorButton);
   toolBar.add(bgcolorButton);
   toolBar.add(helpButton);
   toolBar.add(box_font);
   toolBar.add(box_style);
   toolBar.add(box_size);  // --------------------------------------向容器添加工具栏
   con.add(toolBar, BorderLayout.NORTH);
           
           //*****************************悬浮菜单****************
   final JPopupMenu popupMenu = new JPopupMenu();
    popupMenu_Undo = new JMenuItem("撤消(U)", 'U');
    popupMenu_Cut = new JMenuItem("剪切(T)", 'T');
   popupMenu_Copy = new JMenuItem("复制(C)", 'C');
   popupMenu_Paste = new JMenuItem("粘贴(P)", 'P');
    popupMenu_Delete = new JMenuItem("删除(D)", 'D');
    popupMenu_SelectAll = new JMenuItem("全选(A)", 'A');  popupMenu_Undo.setEnabled(false); // 撤消选项初始设为不可用
  // ---------------向右键菜单添加菜单项和分隔符
   popupMenu.add(popupMenu_Undo);
   popupMenu.addSeparator();
   popupMenu.add(popupMenu_Cut);
   popupMenu.add(popupMenu_Copy);
   popupMenu.add(popupMenu_Paste);
   popupMenu.add(popupMenu_Delete);
   popupMenu.addSeparator();
   popupMenu.add(popupMenu_SelectAll);
   // --------------------右键菜单注册事件
   popupMenu_Undo.addActionListener(this);
   popupMenu_Cut.addActionListener(this);
   popupMenu_Copy.addActionListener(this);
   popupMenu_Paste.addActionListener(this);
   popupMenu_Delete.addActionListener(this);
   popupMenu_SelectAll.addActionListener(this);
          
   area.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
     checkForTriggerEvent(e);
    }   public void mouseReleased(MouseEvent e) {
     checkForTriggerEvent(e);   }
   private void checkForTriggerEvent(MouseEvent e) {
     if (e.isPopupTrigger())
      popupMenu.show(e.getComponent(), e.getX(), e.getY());// 在组件调用者的坐标空间中的位置
                    // X、Y
                    // 显示弹出菜单。
     else {
      statusLabel3.setText("当前光标所在行数: " /*+ getlineNumber()*/);
     }
     //checkMenuItemEnabled(); // 设置剪切、复制、粘贴、删除等功能的可用性
     area.requestFocus(); // 编辑区获取焦点
    }
   });
           
           
    clipboard=this.getToolkit().getSystemClipboard();//获得系统剪切板 
           this.setBounds(250, 127, 650, 495);
           this.setVisible(true);
           this.validate();
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Clock clock = new Clock();
    clock.start();
   
   
  }
  public void actionPerformed(ActionEvent e)
  {
   if(e.getSource()==file_quit)
   {
    dispose();
   }
   if (e.getSource()==file_open || e.getSource() == openButton) {
    {
     JFileChooser chooser=new JFileChooser();
     int state =chooser.showOpenDialog(null);
    File file=chooser.getSelectedFile();
     if(file!=null&&state==JFileChooser.APPROVE_OPTION)
      try{FileInputStream in=new FileInputStream(file);
         DataInputStream  datain=new DataInputStream(in);
      byte b[] =new byte[112];
      int n=-1; 
      area.setText(null);
      while((n=datain.read(b))!=-1)
      {
       String str=new String(b,0,n);
        
       area.append(str); 
      }
      
      this.setTitle(file.getName() + "  - 记事本");
      statusLabel1.setText(" 当前打开文件:" + file.getAbsoluteFile());
      }
     catch(IOException ee)
     {}   
    } 
    
    }
   if(e.getSource()==file_save||e.getSource()==saveButton)
   {
     JFileChooser fileChooser = new JFileChooser();
     fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
     fileChooser.setApproveButtonText("确定");
     fileChooser.setDialogTitle("保存");
     int result = fileChooser.showSaveDialog(this);
     if (result == JFileChooser.CANCEL_OPTION) {
      statusLabel1.setText(" 您没有选择任何文件");
      return;
     }
    File saveFileName = fileChooser.getSelectedFile();
    
     if (saveFileName == null || saveFileName.getName().equals(""))
      JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名", JOptionPane.ERROR_MESSAGE);
     else {
      try{
      FileWriter tofile=new FileWriter(saveFileName);
      BufferedWriter out=new BufferedWriter(tofile);
      out.write(area.getText(), 0, (area.getText().length()));
      this.setTitle(saveFileName.getName() + "  - 记事本");
 //     statusLabel1.setText(" 当前打开文件:" + saveFileName.getAbsoluteFile());
      out.close();
      tofile.close();
     }
     catch(IOException e2)
     {}
     }
     
     
     }
    
   if(e.getSource()==file_asave||e.getSource()==saveAsButton)
   {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setApproveButtonText("确定");
    fileChooser.setDialogTitle("另存为");
    int result = fileChooser.showSaveDialog(this);
    if (result == JFileChooser.CANCEL_OPTION) {
     statusLabel1.setText(" 您没有选择任何文件");
     return;
    }
   File saveFileName = fileChooser.getSelectedFile();
    if (saveFileName == null || saveFileName.getName().equals(""))
     JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名", JOptionPane.ERROR_MESSAGE);
    else {
     try{
     FileWriter tofile=new FileWriter(saveFileName);
     BufferedWriter out=new BufferedWriter(tofile);
     out.write(area.getText(), 0, (area.getText().length()));
     this.setTitle(saveFileName.getName() + "  - 记事本");
 //    statusLabel1.setText(" 当前打开文件:" + saveFileName.getAbsoluteFile());
     out.close();
     tofile.close();
    }
    catch(IOException e2)
    {}
    }
    
   }
    if(e.getSource()==file_new||e.getSource()==newButton)
    { int n=0;
     if(area.getText()!=null)
     {
     n=JOptionPane.showConfirmDialog(this, "文件没有保存,请先保存!","警告",JOptionPane.YES_NO_OPTION);
     }
     if(n==0)
     {
      JOptionPane.showMessageDialog(this, "请按保存按钮进行保存!");
     } 
     if(n==1)
     {
     area.replaceRange("", 0, area.getText().length());
     }
     statusLabel1.setText(" 新建文件" ); 
     
    }
   
   
   if(e.getSource()==format_bcolor||e.getSource()==bgcolorButton)
   {
    Color newColor=JColorChooser.showDialog(this, "选择背景颜色", area.getBackground());
    if(newColor!=null)
     area.setBackground(newColor);
   }
   if(e.getSource()==format_fcolor||e.getSource()==fgcolorButton)
   {
    Color newColor=JColorChooser.showDialog(this, "选择字体颜色", area.getBackground());
    if(newColor!=null)
     area.setForeground(newColor);
   }
   if(e.getSource()==format_linewrap||e.getSource()==italicButton)
   {  if(format_linewrap.getState())
    area.setLineWrap(true);
   else
    area.setLineWrap(false);
    
   }
   if(e.getSource()==fontButton||e.getSource()==format_bold)
   {
    JOptionPane.showMessageDialog(this, "请根据工具栏设置字体","提示",JOptionPane.INFORMATION_MESSAGE);
    
   }
   if(e.getSource()==look_state)
   {
    if (look_state.getState())
     statusBar.setVisible(true);
    else
     statusBar.setVisible(false);
   }
   if(e.getSource()==help_about)
   {
    JOptionPane.showMessageDialog(this,"本记事本为学习而用,请勿用作商业用途!/n李福春","关于",JOptionPane.WARNING_MESSAGE);
   }
   if(e.getSource()==help_help||e.getSource()==helpButton)
   {
    JOptionPane.showMessageDialog(this,"相关的菜单设置了快捷键,工具栏设有提示,不足之处,请指正!","帮助",JOptionPane.WARNING_MESSAGE);
   }
   if(e.getSource()==edit_date||e.getSource()==timeButton)
   {
    area.requestFocus();
    SimpleDateFormat currentDateTime = new SimpleDateFormat("yyyy-MM-dd  HH:mm ");
    area.insert(currentDateTime.format(new Date()),area.getCaretPosition());
    
   }
   if(e.getSource()==edit_selectall||e.getSource()==popupMenu_SelectAll)
   {
    area.selectAll();
   }
   if(e.getSource()==file_print||e.getSource()==printButton)
   {
    PrintJob p=this.getToolkit().getPrintJob(this,"打印", null);
    Graphics g=p.getGraphics();
 //   if(area.getText()!=null)
 //    {
     
     area.printAll(g);
     g.dispose();
    p.end();
 //    }
 //   else 
 //   {
 //    JOptionPane.showConfirmDialog(this, "文本中没有内容,请输入内容进行打印","警告",JOptionPane.YES_NO_OPTION);
 //   } 
       
   }
   if(e.getSource()==popupMenu_Cut||e.getSource()==cutButton||e.getSource()==edit_cut)
   {
    String temp=area.getSelectedText();
    StringSelection text=new StringSelection(temp);
    
    clipboard.setContents(text, null);
    int start=area.getSelectionStart();
    int end=area.getSelectionEnd();
    area.replaceRange("", start, end);
    
   }
   if(e.getSource()==popupMenu_Copy||e.getSource()==edit_copy||e.getSource()==copyButton)
   {
    String temp=area.getSelectedText();
    StringSelection text=new StringSelection(temp);
 //   Clipboard clipboard=this.getToolkit().getSystemClipboard();
    clipboard.setContents(text, null);
 //   int start=area.getSelectionStart();
 //   int end=area.getSelectionEnd();
 //   area.replaceRange("", start, end);
    
   }
   if(e.getSource()==popupMenu_Paste||e.getSource()==edit_paste||e.getSource()==pasteButton)
   {
    Transferable contents=clipboard.getContents(this);
    DataFlavor flavor=DataFlavor.stringFlavor;
    if(contents.isDataFlavorSupported(flavor))
    {
     try{
      String str=(String)contents.getTransferData(flavor);
      area.append(str);
      
     }
     catch(Exception ee)
     {}
     
    }
    
   }
   if(e.getSource()==popupMenu_Delete||e.getSource()==deleteButton||e.getSource()==edit_del)
   {
    int start=area.getSelectionStart();
    int end=area.getSelectionEnd();
    area.replaceRange("", start, end);
    
   }
    
   }
   
   
   
   }
  class Clock extends Thread { // 模拟时钟
   public void run() {
    while (true) {
     GregorianCalendar time = new GregorianCalendar();
     int hour = time.get(Calendar.HOUR_OF_DAY);
     int min = time.get(Calendar.MINUTE);
     int second = time.get(Calendar.SECOND);
     statusLabel2.setText("    当前时间:" + hour + ":" + min + ":" + second);
     try {
      Thread.sleep(950);
     } catch (InterruptedException exception) {
     }   }
   }
  }
   
  public void itemStateChanged(ItemEvent e)
  {
   if(e.getSource()==box_font)
   {
    name=(String)box_font.getSelectedItem();
    f=new Font(name,style,size);
   area.setFont(f);
   
   }
   if(e.getSource()==box_size)
   {
      int r=box_size.getSelectedIndex();
      size=2*r;
    f=new Font(name,style,size);
   area.setFont(f);
   
   }
   if(e.getSource()==box_style)
   {
    if((String) box_style.getSelectedItem()=="加粗")
      style=Font.BOLD;
      
      if((String) box_style.getSelectedItem()=="斜体")
        style=Font.ITALIC;
      if((String) box_style.getSelectedItem()=="常规")
        style=Font.PLAIN;
      if((String) box_style.getSelectedItem()=="粗斜体")
        style=Font.BOLD+Font.ITALIC; 
     f=new Font(name,style,size);
   area.setFont(f);  }
  
   
  } 
    
  /**
   * @param args
   */
  public static void main(String[] args) {
   // TODO Auto-generated method stub
         new TextbookTest("记事本");
  }
 }

举报

相关推荐

0 条评论