2016-09-02 3 views
-2

Я создаю текстовый редактор в качестве побочного проекта, и на данный момент я борется за сохранение и загрузку шрифта, цвета и оформления шрифта текста; другими словами, я могу сохранить только обычный текст. Мой вопрос: как я могу сохранить и загрузить все эти данные?Сохранение шрифта из текстовой панели java

private void Edit() {//This is the method where the program edits the text 
    StyledDocument doc = this.tpText.getStyledDocument(); 
    Style estilo = this.tpText.addStyle("miEstilo", null); 
    StyleConstants.setForeground(estilo, colour); //Color 
    StyleConstants.setFontFamily(estilo, fontLetter);//Letter 
    StyleConstants.setFontSize(estilo, size);//Size 
    StyleConstants.setBold(estilo, bold);//Bold 
    StyleConstants.setItalic(estilo, italics);//Italics 
    StyleConstants.setUnderline(estilo, underline);//Underline 
    doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("miEstilo"), true);//The only text that will be edited is the one that the user highlights 
} 

private void comboxFontsActionPerformed(java.awt.event.ActionEvent evt) {//This is one of the methods in which the program edits the text            
     this.fontLetter = (String) this.comboxFonts.getSelectedItem(); 
     Edit(); 
} 
private void mibtnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//Save as... menu item button            
     int saveResult = fileSelect.showSaveDialog(null); 
      if (saveResult == fileSelect.APPROVE_OPTION) { 
       saveFile(fileSelect.getSelectedFile(), this.tpText.getText()); 
       this.mibtnSave.setEnabled(true); 
      } 
    } 
public void saveFile(File file, String contents) {//Save File 
    BufferedWriter writer = null; 
    String filePath = file.getPath(); 

    try { 
     writer = new BufferedWriter(new FileWriter(filePath)); 
     writer.write(contents); 
     writer.close(); 
     this.tpText.setText(contents); 
     currentFile = file; 
    } catch (Exception e) { 

    } 
} 

public void openFile(File file) {//Load File 
    if (file.canRead()) { 

     String filePath = file.getPath(); 
     String fileContents = ""; 

     if (filePath.endsWith(".txt")) { 
      try { 
       Scanner sc = new Scanner(new FileInputStream(file)); 
       while (sc.hasNextLine()) { 
        fileContents += sc.nextLine(); 
       } 

       sc.close(); 
      } catch (FileNotFoundException e) { 

      } 
      this.tpText.setText(fileContents); 
      currentFile = file; 
     } else { 
      JOptionPane.showMessageDialog(null, "Only .txt files are supported."); 

     } 
    } else { 
     JOptionPane.showMessageDialog(null, "Could not open file..."); 
    } 
} 

ответ

0

Я не знаю, если я получил свой вопрос прямо, но если вы пытаетесь сохранить стиль помимо обычного текста, вы можете сделать следующее.
Сохраните все атрибуты стиля в другом файле рядом с текстовым файлом, и вы сможете восстановить его при открытии текстового файла.

+0

Я тоже об этом думал, но вот проблема: скажем, текст «привет мир», «привет» часть смелая, а «мир» - курсив. "** hello ** _world_" Я хочу знать, как я могу сохранить и загрузить такой текст. – RMorazan

+0

Хорошо, позвольте мне предложить что-нибудь вам, мой друг .. , когда любой пользователь пытается создать стиль текста, сохраните этот стиль в строке, а затем напишите его в файл рядом с сохраненным открытым текстом. Пример: При нажатии на полужирную или курсивную кнопку, чтобы сделать hello жирным шрифтом, а мир курсивом, ваша строка должна быть примерно такой: «строка X col Y word 'hello' bold" где 'X и Y' - это позиция слово в тексте –

Смежные вопросы