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

📄 jexttextarea.java

📁 java写的多功能文件编辑器
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
      }    }  }  /**   * Set a new file. We first ask the user if he'd like to save its   * changes (if some have been made).   */  public void newFile()  {    beginOperation();                            // we don't want to see a 'modified' message    if (isDirty() && !isEmpty())    {      String[] args = { getName() };      int response = JOptionPane.showConfirmDialog(parent,                                                   Jext.getProperty("general.save.question", args),                                                   Jext.getProperty("general.save.title"),                                                   JOptionPane.YES_NO_CANCEL_OPTION,                                                   JOptionPane.QUESTION_MESSAGE);      switch (response)      {        case 0:          saveContent();          break;        case 1:          break;        case 2:          endOperation();          return;        default:          endOperation();          return;      }    }    // we have to create a new document, so we remove    // old listeners and create new ones below    document.removeUndoableEditListener(this);    document.removeDocumentListener(this);    clean();    discard();    setEditable(true);    setText("");    anchor = null;    modTime = -1;    newf = true;    resetLineTerm();    currentFile = null;    searchHighlight = null;    document.addUndoableEditListener(this);    document.addDocumentListener(this);    parent.setNew(this);    parent.setTextAreaName(this, Jext.getProperty("textarea.untitled"));    parent.fireJextEvent(this, JextEvent.FILE_CLEARED);    setParentTitle();    endOperation();  }  /**   * This is called by the AutoSave thread.   */  public void autoSave()  {    if (!isNew())      saveContent();  }  /**   * This overrides standard insert method. Indeed, we need   * to update the label containing caret's position.   * @param insert The string to insert   * @param pos The offset of the text where to insert the string   */  public void insert(String insert, int pos)  {    setCaretPosition(pos);    setSelectedText(insert);  }  public void userInput(char c)  {    String indentOpenBrackets = getProperty("indentOpenBrackets");    String indentCloseBrackets = getProperty("indentCloseBrackets");    if ((indentCloseBrackets != null && indentCloseBrackets.indexOf(c) != -1) ||        (indentOpenBrackets != null && indentOpenBrackets.indexOf(c) != -1))    {      org.jext.misc.Indent.indent(this, getCaretLine(), false, true);    }  }  /**   * Because JEditorPane doesn't have any getTabSize() method,   * we implement our own one.   * @return Current tab size (in amount of spaces)   */  public int getTabSize()  {    String size = Jext.getProperty("editor.tabSize");    if (size == null)      return 8;    Integer i = new Integer(size);    if (i != null)      return i.intValue();    else      return 8;  }  /**   * See getTabSize().   * @param size The new tab size (in amount of spaces)   */  public void setTabSize(int size)  {    //Jext.setProperty("editor.tabSize", String.valueOf(size));    document.putProperty(PlainDocument.tabSizeAttribute,  new Integer(size));  }  /**   * Set parent title according to the fullfilename flag   * in the user properties.   */  public void setParentTitle()  {    if (currentFile == null)    {      Workspaces ws = parent.getWorkspaces();      parent.setTitle("Jext - " + Jext.getProperty("textarea.untitled") +                      (ws == null ? "" : " [" + ws.getName() + ']'));      return;    }    String fName;    if (Jext.getBooleanProperty("full.filename", "off"))      fName = Utilities.getShortStringOf(currentFile, 80);    else      fName = getFileName(currentFile);    Workspaces ws = parent.getWorkspaces();    parent.setTitle("Jext - " + fName + (ws == null ? "" : " [" + ws.getName() + ']'));  }  // get the name of a file from its absolute path name  private String getFileName(String file)  {    if (file == null)      return Jext.getProperty("textarea.untitled");    else      return file.substring(file.lastIndexOf(File.separator) + 1);  }  /**   * Get name of this text area. This name is made of the current opened   * file name.   */  public String getName()  {    return getFileName(currentFile);  }  /**   * Turn syntax colorization on or off.   * @param mode Colorization mode   */  public void setColorizing(String mode)  {    enableColorizing(mode, Jext.getMode(mode).getTokenMarker());  }  public void setColorizing(Mode mode)  {    enableColorizing(mode.getModeName(), mode.getTokenMarker());  }  private void enableColorizing(String mode, TokenMarker token)  {    if (mode == null || token == null || mode.equals(this.mode))      return;    setTokenMarker(token);    this.mode = mode;    getPainter().setBracketHighlightEnabled("on".equals(getProperty("bracketHighlight")));    Jext.setProperty("editor.colorize.mode", mode);    parent.fireJextEvent(this, JextEvent.SYNTAX_MODE_CHANGED);    repaint();  }  /**   * Sets current colorizing mode.   * @param mode The colorizing mode name   */  public void setColorizingMode(String mode)  {    this.mode = mode;  }  /**   * Returns current syntax colorizing mode.   */  public String getColorizingMode()  {    return mode;  }  /**   * Checks if holded file has been changed by an external program.   */  public void checkLastModificationTime()  {    if (modTime == -1)      return;    File file = getFile();    if (file == null)      return;    long newModTime = file.lastModified();    if (newModTime > modTime)    {      String prop = (isDirty() ? "textarea.filechanged.dirty.message" : "textarea.filechanged.focus.message");      Object[] args = { currentFile };      int result = JOptionPane.showConfirmDialog(parent,                                                Jext.getProperty(prop, args),                                                Jext.getProperty("textarea.filechanged.title"),                                                JOptionPane.YES_NO_OPTION,                                                JOptionPane.WARNING_MESSAGE);      if (result == JOptionPane.YES_OPTION)        open(currentFile);      else        modTime = newModTime;    }  }  /**   * Called to save current content in specified zip file.   * Call zip(String file) but asks user for overwriting if   * file already exists.   */  public void zipContent()  {    if (getText().length() == 0)      return;    if (isNew())    {      Utilities.showMessage("Please save your file before zipping it !");      return;    }    String zipFile = Utilities.chooseFile(parent, Utilities.SAVE);    if (zipFile != null)    {      if (!zipFile.endsWith(".zip"))        zipFile += ".zip";      if (!(new File(zipFile)).exists())        zip(zipFile);      else      {        int response = JOptionPane.showConfirmDialog(parent,                                                     Jext.getProperty("textarea.file.exists", new Object[] { zipFile }),                                                     Jext.getProperty("general.save.title"),                                                     JOptionPane.YES_NO_OPTION,                                                     JOptionPane.QUESTION_MESSAGE);        switch (response)        {          case 0:            zip(zipFile);            break;          case 1:            break;          default:            return;        }      }    }  }  /**   * Zip text area content into specified file.   * @param zipFile The file name where to zip the text   */  public void zip(String zipFile)  {    waitingCursor(true);    try    {      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));      out.putNextEntry(new ZipEntry((new File(currentFile)).getName()));      // we ensured we use system's carriage return char, as in save():      //String newline = Jext.getProperty("editor.newLine");//System.getProperty("line.separator");      //but now, as in save(), we use document's one.      String newline = getLineTerm();      Element map = document.getDefaultRootElement();      // we zip the text line by line      for (int i = 0; i < map.getElementCount() ; i++)      {        Element line = map.getElement(i);        int start = line.getStartOffset();        byte[] buf = (getText(start, line.getEndOffset() - start - 1) + newline).getBytes();        out.write(buf, 0, buf.length);      }      out.closeEntry();      out.close();    } catch(IOException ioe) {      Utilities.showError(Jext.getProperty("textarea.zip.error"));    }    waitingCursor(false);  }  /**   * Called to save this component's content.   * Call save(String file) but let the user choosing a file name   * if the isNew() flag is true (int the case the user choosed   * an existing file, we ask him if he really wants to overwrite it).   */  public void saveContent()  {    if (!isEditable())      return;    if (isNew())    {      String fileToSave = Utilities.chooseFile(parent, Utilities.SAVE);      if (fileToSave != null)      {        if (!(new File(fileToSave)).exists())          save(fileToSave);        else        {          int response = JOptionPane.showConfirmDialog(parent,                         Jext.getProperty("textarea.file.exists", new Object[] { fileToSave }),                         Jext.getProperty("general.save.title"),                         JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);          switch (response)          {            case 0:              save(fileToSave);              break;            case 1:              break;            default:              return;          }        }      }    } else {      if (isDirty())        save(currentFile);    }  }  /**   * Store the text in a specified file.   * @param file The file in which we'll write the text   */  public void save(String file)  {    waitingCursor(true);    try    {      File _file = new File(file);      long newModTime = _file.lastModified();      if (modTime != -1 && newModTime > modTime)      {        int result = JOptionPane.showConfirmDialog(parent,                     Jext.getProperty("textarea.filechanged.save.message", new Object[] { file }),                     Jext.getProperty("textarea.filechanged.title"),                     JOptionPane.YES_NO_OPTION,                     JOptionPane.WARNING_MESSAGE);        if (result != JOptionPane.YES_OPTION)        {          waitingCursor(false);          return;        }      }      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(                           new FileOutputStream(_file),                           Jext.getProperty("editor.encoding", System.getProperty("file.encoding"))),                           BUFFER_SIZE);      Segment lineSegment = new Segment();      //String newline = Jext.getProperty("editor.newLine");      String newline = getLineTerm();      Element map = document.getDefaultRootElement();      // we save the text line by line      for (int i = 0; i < map.getElementCount() - 1; i++)      {        Element line = map.getElement(i);        int start = line.getStartOffset();        document.getText(start, line.getEndOffset() - start - 1, lineSegment);        out.write(lineSegment.array, lineSegment.offset, lineSegment.count);        out.write(newline);      }      // avoids extra line feed at the end of the file      Element line = map.getElement(map.getElementCount() - 1);      int start = line.getStartOffset();      document.getText(start, line.getEndOffset() - start - 1, lineSegment);      out.write(lineSegment.array, lineSegment.offset, lineSegment.count);      if (Jext.getBooleanProperty("editor.extra_line_feed"))        out.write(newline);      out.close();      storeOrigLineTerm(); //so we can see if it has been changed.      if (!file.equals(currentFile))      {        parent.setTextAreaName(this, getFileName(file));        parent.saveRecent(file);        currentFile = file;        setParentTitle();      }      _file = new File(file);      modTime = _file.lastModified();      if (isNew())        newf = false;      clean(); //reset the dirty flag      parent.setSaved(this);    } catch(Exception e) {      Utilities.showError(Jext.getProperty("textarea.save.error"));    }    waitingCursor(false);  }  /**   * Called to load a new file in the text area.   * Determines which line separator (\n, \r\n...) are used in the   * file to open. Convert'em into Swing line separator (\n).   * @param path The path of the file to be loaded   */  public void open(String path)  {    open(path, null, 0);  }  /**   * Called to load a new file in the text area.   * Determines which line separator (\n, \r\n...) are used in the   * file to open. Convert'em into Swing line separator (\n).   * @param path The path of the file to be loaded   * @param addToRecentList If false, the file name is not added to recent list   */  public void open(String path, boolean addToRecentList)  {    open(path, null, 0, false, addToRecentList);  }  /**   * Called to load a new file in the text area.   * Determines which line separator (\n, \r\n...) are used in the   * file to open. Convert'em into Swing line separator (\n).   * @param path The path of the file to be loaded   * @param _in You can specify an InputStreamReader (see ZipExplorer)   * @param bufferSize Size of the StringBuffer, useful if _in != null   */  public void open(String path, InputStreamReader _in, int bufferSize)  {    open(path, _in, bufferSize, false, true);  }  /**   * Called to load a new file in the text area.   * Determines which line separator (\n, \r\n...) are used in the   * file to open. Convert'em into Swing line separator (\n).   * @param path The path of the file to be loaded   * @param _in You can specify an InputStreamReader (see ZipExplorer);   * if you do this the TextArea is marked as 'dirty'   * @param bufferSize Size of the StringBuffer, useful if _in != null   * @param web True if open an url   * @param addToRecentList If false, the file name is not added to recent list   */  public void open(String path, InputStreamReader _in, int bufferSize,                   boolean web, boolean addToRecentList)  {    beginOperation();    if (path.endsWith(".zip") || path.endsWith(".jar"))    {      new ZipExplorer(parent, this, path);      endOperation();      return;    }    // we do the same thing as in newFile() for the listeners    document.removeUndoableEditListener(this);    document.removeDocumentListener(this);    clean();    discard();    anchor = null;    modTime = -1;    try    {      StringBuffer buffer;      InputStreamReader in;      if (_in== null)      {        File toLoad = new File(path);        // we check if the file is read only or not        if (!toLoad.canWrite())          setEditable(false);        else if (!isEditable())

⌨️ 快捷键说明

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