⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simpletexteditor.java

📁 这是一个小的文件编辑器
💻 JAVA
字号:
import javax.swing.*;
//import javax.swing.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.text.Document;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
//import com.borland.dbswing.*;

//import com.borland.dbswing.*;
public class SimpleTextEditor extends JFrame
    implements ActionListener,DocumentListener
{ //IntlSwingSupport intlSwingSupport1=new InterruptedException();
    //Jpanel contentPane;
    private JMenuBar mBar = new JMenuBar();
    private JMenu fileMenu, editMenu, formatMenu,helpMenu,cutsMenu;
    private JMenuItem newItem, openItem, saveItem,saveAsItem,quitItem;
    private JMenuItem cutItem, copyItem, pasteItem, selectItem;
    private JMenuItem fontItem,colorItem;
    private JMenuItem aboutItem;
    private JMenuItem recentcutItem;

    private JTextArea display = new JTextArea();//创建文本区域
    private String scratchPad = " ";//当前剪掉的内容
    private Vector recentCuts = new Vector();//最近剪切的内容
    private JFileChooser jFileChooser1= new JFileChooser();//文件选择对话框
    //private FontChooser fontChooser1 = new FontChooser();
    Document document1 = display.getDocument();//文本区域的文档对象
    JLabel  statusBar = new JLabel();//状态栏对象
    String currFileName=null;//当前文件名
    boolean dirty=false;//存储文件是否被修改过信息
   // Doucument doucument1=new Doucument
    //display.addDoucumentListener(this);



    public SimpleTextEditor()
    {
        super("Simple Text Editor");//设置当前容器面板
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add("Center", display);
        this.getContentPane().add(new JScrollPane(display));
        this.getContentPane().add(statusBar,BorderLayout.SOUTH);
        display.setLineWrap(true);//自动换行
        this.setJMenuBar(mBar);
        initFileMenu();
        initEditMenu();
        initFormatMenu();
        initAboutMenu();
        updateCaption();

    }
    private void initFileMenu()
   {
       fileMenu = new JMenu("File");
       mBar.add(fileMenu);
       newItem = new JMenuItem("New");
       newItem.addActionListener(this);
       fileMenu.add(newItem);
       openItem = new JMenuItem("Open");
       openItem.addActionListener(this);
       openItem.setEnabled(true);
       fileMenu.add(openItem);
       saveItem = new JMenuItem("Save");
       saveItem.addActionListener(this);
       saveItem.setEnabled(true);
       fileMenu.add(saveItem);
       saveAsItem = new JMenuItem("Save As");
       saveAsItem.addActionListener(this);
       saveAsItem.setEnabled(true);
       fileMenu.add(saveAsItem);

       fileMenu.addSeparator();
       quitItem = new JMenuItem("Quit");
       quitItem.addActionListener(this);
       fileMenu.add(quitItem);
       document1.addDocumentListener(this);
   }


    private void initEditMenu()
    {
        editMenu = new JMenu("Edit");
        mBar.add(editMenu);
        cutItem = new JMenuItem("Cut");
        cutItem.addActionListener(this);
        editMenu.add(cutItem);
        copyItem = new JMenuItem("Copy");
        copyItem.addActionListener(this);
        editMenu.add(copyItem);
        pasteItem = new JMenuItem("Paste");
        pasteItem.addActionListener(this);
        editMenu.add(pasteItem);
        editMenu.addSeparator();
        selectItem = new JMenuItem("Select All");
        selectItem.addActionListener(this);
        editMenu.add(selectItem);
        editMenu.addSeparator();
        cutsMenu = new JMenu("Recent Cuts");
        editMenu.add(cutsMenu);
        recentcutItem=new JMenu("Recent");
        recentcutItem.addActionListener(this);
        cutsMenu.add(recentcutItem);

    }

        private void initFormatMenu()
        {
          formatMenu = new JMenu("Format");
          mBar.add(formatMenu);
          fontItem = new JMenuItem("Font");
          fontItem.addActionListener(this);
          formatMenu.add(fontItem);
          colorItem = new JMenuItem("Color");
          colorItem.addActionListener(this);
          formatMenu.add(colorItem);
    }

    private void initAboutMenu()
   {
       helpMenu = new JMenu("Help");
       mBar.add(helpMenu);
       aboutItem = new JMenuItem("About");
       aboutItem.addActionListener(this);
       helpMenu.add(aboutItem);
  }


    public void actionPerformed(ActionEvent e)
    {
        JMenuItem m = (JMenuItem)e.getSource();
        if(m == quitItem)
        {
            dispose();
            System.exit(0);
        }
        else if (m == cutItem)
        {
            scratchPad = display.getSelectedText();
            display.replaceRange("",
            display.getSelectionStart(),
            display.getSelectionEnd());
            addRecentCut(scratchPad);//加入到向量中
        }
        else if (m == copyItem)
        {
            scratchPad = display.getSelectedText();
        }
        else if (m == pasteItem)
        {
            display.insert(scratchPad,display.getCaretPosition());
        }
        else if (m == selectItem)
        {
            display.selectAll();
        }
        else if(m==newItem)//处理“新建”菜单项
        {
          if(okToAbandon()){  //okToAbandon()返回true时代码被执行
            display.setText(" ");//清空文本区域
          currFileName=null;
          dirty=false;//文本未修改
          updateCaption();//更新标题栏

          }


        }
        else if(m==openItem)
        { if(!okToAbandon()){  //okToAbandon()返回false时直接退出
            return;
          }
          if(JFileChooser.APPROVE_OPTION==jFileChooser1.showOpenDialog(this))
          {
                 openFile(jFileChooser1.getSelectedFile().getPath());
                 this.repaint();
          } 
          }
        else if(m==saveItem)
        {
          saveFile();
        }
        else if(m==saveAsItem)
        {
          saveAsFile();
        }
        else if(m==quitItem)//退出处理
        {
          if(okToAbandon()){
            System.exit(0);
          }
        }
        else
        {
            JMenuItem item = (JMenuItem)e.getSource();
            scratchPad = item.getActionCommand();
        }
    }
   //在窗口的标题栏显示文件名和状态
   void updateCaption(){
     String caption;
     if(currFileName==null)
     {
       //synthesize the "Untitled"name if no name yet.
       caption="Untitled";

     }
   else{
     caption=currFileName;

   }
 if(dirty){
   caption = "*" + caption;
 }
 caption="Text Editor-"+caption;
 this.setTitle(caption);
   }


    //以下是将事件处理与文本区联系起来
   public void changedUpdate(DocumentEvent e){
     if(!dirty){
       dirty = true;
      updateCaption();
     }

    }
   public void insertUpdate(DocumentEvent e){
     if(!dirty){
        dirty = true;
       updateCaption();
      }

   }
  public void removeUpdate(DocumentEvent e){
    if(!dirty){
      dirty = true;
     updateCaption();
    }

    }
    private void openFile(String fileName)
    {
      try{
        File file=new File(fileName);//创建文件类的对象
        int size=(int)file.length();
        int chars_read=0;
        FileReader in=new FileReader(file);//创建文件读取器的对象(字符流)
        char[] data=new char[size];
        while(in.ready()){
          chars_read += in.read(data, chars_read,size - chars_read);
//read (byte b[], int off, int len) Reads up to len bytes of data starting from offset off from the input stream into an array.
//返回读取字符的长度
        }
        in.close();
        display.setText(new String(data,0,chars_read));
        statusBar.setText("Opend"+fileName);
        updateCaption();

      }catch(IOException e)
      {
        statusBar.setText("Error opening"+fileName);
      }
    }
    private boolean saveFile()
   {if(currFileName==null)
     {
       return saveAsFile();
     }
     try{
       File file=new File(currFileName);;
       FileWriter out=new FileWriter(file);//创建写入器的对象
       String text=display.getText();
       out.write(text);
       out.close();
       this.dirty=false;
       statusBar.setText("Saved to"+currFileName);
       updateCaption();
      return true;
      }catch(IOException e)
     {
       statusBar.setText("Error saveing"+currFileName);
     }
  return false;
   }

   private boolean saveAsFile()
    {if(JFileChooser.APPROVE_OPTION==jFileChooser1.showSaveDialog(this))
      {
        currFileName=jFileChooser1.getSelectedFile().getPath();
        this.repaint();
        return saveFile();
      }
      else{
        this.repaint();
        return false;
      }

     }
boolean okToAbandon(){   //测试文件是否被修改
  if(!dirty)
  {
    return true;
  }
  int value=JOptionPane.showConfirmDialog(this,"Save changes?","Text Edit",JOptionPane.YES_NO_CANCEL_OPTION);
switch(value){
  case JOptionPane.YES_OPTION:
    return saveFile();
    case JOptionPane.NO_OPTION:
      return true;
      case JOptionPane.CANCEL_OPTION:
        default:
          return false;

}}
    private void addRecentCut(String cut)
    {
        recentCuts.insertElementAt(cut,0);
        cutsMenu.removeAll();
        for(int i=0; i<recentCuts.size(); i++)
        {
            JMenuItem item = new JMenuItem(
                (String)recentCuts.elementAt(i));
            cutsMenu.add(item);
            item.addActionListener(this);
        }
    }


    public static void main(String args[])
    {
        SimpleTextEditor f = new SimpleTextEditor();
        f.setSize(300,200);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we)  {
                System.exit(0);
            }
        });
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -