public void saveDocumentAs(){
view.selectHtmlTab();
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileFilter(new HTMLFileFilter());
int index = jFileChooser.showDialog(view, "Save File");
if(index == JFileChooser.APPROVE_OPTION){
currentFile = jFileChooser.getSelectedFile();
try(FileOutputStream fileOutputStream = new FileOutputStream(currentFile)) {
fileOutputStream.write(getDocument().getText(0, getDocument().getLength()).getBytes());
} catch (FileNotFoundException e) {
ExceptionHandler.log(e);
} catch (IOException e) {
ExceptionHandler.log(e);
} catch (BadLocationException e) {
ExceptionHandler.log(e);
}
}
}
package com.javarush.task.task32.task3209;
import com.javarush.task.task32.task3209.listeners.UndoListener;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import java.io.*;
public class Controller {
private View view;
private HTMLDocument document;
private File currentFile;
public Controller(View view) {
this.view = view;
}
public HTMLDocument getDocument() {
return document;
}
public void init(){
createNewDocument();
}
public void exit(){
System.exit(0);
}
public void resetDocument(){
if(document!=null){
document.removeUndoableEditListener(view.getUndoListener());
}
document = (HTMLDocument) new HTMLEditorKit().createDefaultDocument();
document.addUndoableEditListener(view.getUndoListener());
view.update();
}
public void setPlainText(String text){
resetDocument();
StringReader stringReader = new StringReader(text);
try {
new HTMLEditorKit().read(stringReader, document,0);
} catch (IOException | BadLocationException e) {
ExceptionHandler.log(e);
}
}
public String getPlainText(){
StringWriter stringWriter = new StringWriter();
try {
new HTMLEditorKit().write(stringWriter, document,0,document.getLength());
} catch (IOException | BadLocationException e) {
ExceptionHandler.log(e);
}
return stringWriter.toString();
}
public void createNewDocument(){
view.selectHtmlTab();
view.setTitle("HTML редактор");
view.resetUndo();
currentFile = null;
resetDocument();
}
public void openDocument(){
}
public void saveDocument(){
}
public void saveDocumentAs(){
view.selectHtmlTab();
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileFilter(new HTMLFileFilter());
int index = jFileChooser.showDialog(view, "Save File");
if(index == JFileChooser.APPROVE_OPTION){
currentFile = jFileChooser.getSelectedFile();
try(FileOutputStream fileOutputStream = new FileOutputStream(currentFile)) {
fileOutputStream.write(getDocument().getText(0, getDocument().getLength()).getBytes());
} catch (FileNotFoundException e) {
ExceptionHandler.log(e);
} catch (IOException e) {
ExceptionHandler.log(e);
} catch (BadLocationException e) {
ExceptionHandler.log(e);
}
}
}
public static void main(String[] args) {
View view = new View();
Controller controller = new Controller(view);
view.setController(controller);
view.init();
controller.init();
}
}