Created
December 16, 2018 22:43
-
-
Save Shtaba09/3e6b924268640625d93cb7547e69bb6c to your computer and use it in GitHub Desktop.
HTML EDITOR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.actions; | |
import com.javarush.task.task32.task3209.View; | |
import javax.swing.*; | |
import java.awt.event.ActionEvent; | |
public class RedoAction extends AbstractAction { | |
private View view; | |
public RedoAction(View view) { | |
this.view = view; | |
} | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
view.redo(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.actions; | |
import javax.swing.*; | |
import javax.swing.text.MutableAttributeSet; | |
import javax.swing.text.SimpleAttributeSet; | |
import javax.swing.text.StyleConstants; | |
import javax.swing.text.StyledEditorKit; | |
import java.awt.event.ActionEvent; | |
public class StrikeThroughAction extends StyledEditorKit.StyledTextAction { | |
public StrikeThroughAction() { | |
super(StyleConstants.StrikeThrough.toString()); | |
} | |
public void actionPerformed(ActionEvent actionEvent) { | |
JEditorPane editor = getEditor(actionEvent); | |
if (editor != null) { | |
MutableAttributeSet mutableAttributeSet = getStyledEditorKit(editor).getInputAttributes(); | |
SimpleAttributeSet simpleAttributeSet = new SimpleAttributeSet(); | |
StyleConstants.setStrikeThrough(simpleAttributeSet, !StyleConstants.isStrikeThrough(mutableAttributeSet)); | |
setCharacterAttributes(editor, simpleAttributeSet, false); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.actions; | |
import javax.swing.*; | |
import javax.swing.text.MutableAttributeSet; | |
import javax.swing.text.SimpleAttributeSet; | |
import javax.swing.text.StyleConstants; | |
import javax.swing.text.StyledEditorKit; | |
import java.awt.event.ActionEvent; | |
public class SubscriptAction extends StyledEditorKit.StyledTextAction { | |
/** | |
* Creates a new StyledTextAction from a string action name. | |
* | |
* @param nm the name of the action | |
*/ | |
public SubscriptAction(String nm) { | |
super(nm); | |
} | |
public SubscriptAction() { | |
super(StyleConstants.Subscript.toString()); | |
} | |
@Override | |
public void actionPerformed(ActionEvent actionEvent) { | |
JEditorPane editor = getEditor(actionEvent); | |
if (editor != null) { | |
MutableAttributeSet mutableAttributeSet = getStyledEditorKit(editor).getInputAttributes(); | |
SimpleAttributeSet simpleAttributeSet = new SimpleAttributeSet(); | |
StyleConstants.setSubscript(simpleAttributeSet, !StyleConstants.isSubscript(mutableAttributeSet)); | |
setCharacterAttributes(editor, simpleAttributeSet, false); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.actions; | |
import javax.swing.*; | |
import javax.swing.text.MutableAttributeSet; | |
import javax.swing.text.SimpleAttributeSet; | |
import javax.swing.text.StyleConstants; | |
import javax.swing.text.StyledEditorKit; | |
import java.awt.event.ActionEvent; | |
public class SuperscriptAction extends StyledEditorKit.StyledTextAction { | |
/** | |
* Creates a new StyledTextAction from a string action name. | |
* | |
* @param nm the name of the action | |
*/ | |
public SuperscriptAction(String nm) { | |
super(nm); | |
} | |
public SuperscriptAction() { | |
super(StyleConstants.Superscript.toString()); | |
} | |
@Override | |
public void actionPerformed(ActionEvent actionEvent) { | |
JEditorPane editor = getEditor(actionEvent); | |
if (editor != null) { | |
MutableAttributeSet mutableAttributeSet = getStyledEditorKit(editor).getInputAttributes(); | |
SimpleAttributeSet simpleAttributeSet = new SimpleAttributeSet(); | |
StyleConstants.setSuperscript(simpleAttributeSet, !StyleConstants.isSuperscript(mutableAttributeSet)); | |
setCharacterAttributes(editor, simpleAttributeSet, false); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.actions; | |
import com.javarush.task.task32.task3209.View; | |
import javax.swing.*; | |
import java.awt.event.ActionEvent; | |
public class UndoAction extends AbstractAction { | |
private View view; | |
public UndoAction(View view) { | |
this.view = view; | |
} | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
view.undo(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209; | |
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 static void main (String[] args ){ | |
View view = new View(); | |
Controller controller =new Controller(view); | |
view.setController(controller); | |
view.init(); | |
controller.init(); | |
} | |
public void init(){ | |
createNewDocument(); | |
} | |
public void exit(){System.exit(0);} | |
public HTMLDocument getDocument() { | |
return document; | |
} | |
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 e) { | |
ExceptionHandler.log(e); | |
} catch (BadLocationException e) { | |
ExceptionHandler.log(e); | |
} | |
} | |
public String getPlainText(){ | |
StringWriter stringWriter = new StringWriter(); | |
try { | |
new HTMLEditorKit().write(stringWriter, document, 0, document.getLength()); | |
} catch (IOException e) { | |
ExceptionHandler.log(e); | |
} catch (BadLocationException e) { | |
ExceptionHandler.log(e); | |
} | |
return stringWriter.toString(); | |
} | |
public void createNewDocument() { | |
view.selectHtmlTab(); | |
resetDocument(); | |
view.setTitle("HTML редактор"); | |
view.resetUndo(); | |
currentFile=null; | |
} | |
public void openDocument() { | |
view.selectHtmlTab(); | |
JFileChooser fileChooser = new JFileChooser(); | |
fileChooser.setFileFilter(new HTMLFileFilter()); | |
if(fileChooser.showOpenDialog(view) == JFileChooser.APPROVE_OPTION){ | |
currentFile=fileChooser.getSelectedFile(); | |
resetDocument(); | |
view.setTitle(currentFile.getName()); | |
try (FileReader reader = new FileReader(currentFile)) { | |
new HTMLEditorKit().read(reader,document,0); | |
view.resetUndo(); | |
} catch (BadLocationException | IOException e) { | |
ExceptionHandler.log(e); | |
} | |
} | |
} | |
public void saveDocument() { | |
view.selectHtmlTab(); | |
if(currentFile==null){saveDocumentAs(); } else { | |
try (FileWriter writer = new FileWriter(currentFile)) { | |
new HTMLEditorKit().write(writer, document, 0, document.getLength()); | |
} catch (BadLocationException | IOException e) { | |
ExceptionHandler.log(e);} | |
} | |
} | |
public void saveDocumentAs() { | |
view.selectHtmlTab(); | |
JFileChooser fileChooser = new JFileChooser(); | |
fileChooser.setFileFilter(new HTMLFileFilter()); | |
if (fileChooser.showSaveDialog(view) == JFileChooser.APPROVE_OPTION) { | |
currentFile = fileChooser.getSelectedFile(); | |
view.setTitle(currentFile.getName()); | |
try (FileWriter writer = new FileWriter(currentFile)) { | |
new HTMLEditorKit().write(writer, document, 0, document.getLength()); | |
} catch (BadLocationException | IOException e) { | |
ExceptionHandler.log(e); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209; | |
public class ExceptionHandler { | |
public static void log(Exception e){ | |
System.out.println(e.toString()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209; | |
import javax.swing.filechooser.FileFilter; | |
import java.io.File; | |
public class HTMLFileFilter extends FileFilter { | |
@Override | |
public boolean accept(File f) { | |
if(f.isDirectory()){return true;} else | |
if (f.getName().toLowerCase().endsWith(".html")||f.getName().toLowerCase().endsWith(".htm")) {return true;} | |
return false; | |
} | |
@Override | |
public String getDescription() { | |
return "HTML и HTM файлы"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.listeners; | |
import com.javarush.task.task32.task3209.View; | |
import javax.swing.event.ChangeEvent; | |
import javax.swing.event.ChangeListener; | |
import java.awt.event.WindowAdapter; | |
import java.awt.event.WindowEvent; | |
public class FrameListener extends WindowAdapter implements ChangeListener { | |
private View view; | |
public FrameListener(View view) { | |
this.view = view; | |
} | |
@Override | |
public void windowClosing(WindowEvent e) { | |
view.exit(); | |
} | |
@Override | |
public void stateChanged(ChangeEvent e) { | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.listeners; | |
import com.javarush.task.task32.task3209.View; | |
import javax.swing.event.ChangeEvent; | |
import javax.swing.event.ChangeListener; | |
public class TabbedPaneChangeListener implements ChangeListener { | |
private View view; | |
public TabbedPaneChangeListener(View view) { | |
this.view = view; | |
} | |
@Override | |
public void stateChanged(ChangeEvent e) { | |
view.selectedTabChanged(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209.listeners; | |
import javax.swing.event.UndoableEditEvent; | |
import javax.swing.event.UndoableEditListener; | |
import javax.swing.undo.UndoManager; | |
public class UndoListener implements UndoableEditListener { | |
private UndoManager undoManager; | |
public UndoListener(UndoManager undoManager) { | |
this.undoManager = undoManager; | |
} | |
@Override | |
public void undoableEditHappened(UndoableEditEvent e) { | |
undoManager.addEdit(e.getEdit()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javarush.task.task32.task3209; | |
import com.javarush.task.task32.task3209.listeners.FrameListener; | |
import com.javarush.task.task32.task3209.listeners.UndoListener; | |
import com.sun.org.apache.bcel.internal.generic.SWITCH; | |
import javax.swing.*; | |
import javax.swing.undo.CannotRedoException; | |
import javax.swing.undo.CannotUndoException; | |
import javax.swing.undo.UndoManager; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
public class View extends JFrame implements ActionListener { | |
private Controller controller; | |
private FrameListener listener; | |
private JTabbedPane tabbedPane = new JTabbedPane(); | |
private JTextPane htmlTextPane = new JTextPane(); | |
private JEditorPane plainTextPane = new JEditorPane(); | |
private UndoManager undoManager = new UndoManager(); | |
private UndoListener undoListener = new UndoListener(undoManager); | |
public View (){ | |
try { | |
UIManager.setLookAndFeel(""); | |
} catch (ClassNotFoundException e) { | |
ExceptionHandler.log(e); | |
} catch (InstantiationException e) { | |
ExceptionHandler.log(e); | |
} catch (IllegalAccessException e) { | |
ExceptionHandler.log(e); | |
} catch (UnsupportedLookAndFeelException e) { | |
ExceptionHandler.log(e); | |
} | |
} | |
public Controller getController() { | |
return controller; | |
} | |
public void setController(Controller controller) { | |
this.controller = controller; | |
} | |
public void init(){ | |
initGui(); | |
listener = new FrameListener(this); | |
addWindowListener(listener); | |
setVisible(true); | |
} | |
public void initMenuBar(){ | |
JMenuBar menuBar = new JMenuBar(); | |
MenuHelper.initFileMenu(this, menuBar); | |
MenuHelper.initEditMenu(this, menuBar); | |
MenuHelper.initStyleMenu(this, menuBar); | |
MenuHelper.initAlignMenu(this, menuBar); | |
MenuHelper.initColorMenu(this, menuBar); | |
MenuHelper.initFontMenu(this, menuBar); | |
MenuHelper.initHelpMenu(this, menuBar); | |
getContentPane().add(menuBar, BorderLayout.NORTH); | |
} | |
public void initEditor(){ | |
htmlTextPane.setContentType("text/html"); | |
JScrollPane jScrollPane = new JScrollPane(htmlTextPane); | |
tabbedPane.add("HTML",jScrollPane); | |
JScrollPane jScrollPane1 = new JScrollPane(plainTextPane); | |
tabbedPane.add("Текст",jScrollPane1); | |
tabbedPane.setPreferredSize(new Dimension(800,600)); | |
tabbedPane.addChangeListener(listener); | |
getContentPane().add(tabbedPane, BorderLayout.CENTER); | |
} | |
public void initGui(){ | |
initMenuBar(); | |
initEditor(); | |
pack(); | |
} | |
public void exit(){controller.exit();} | |
@Override | |
public void actionPerformed(ActionEvent actionEvent) { | |
String action = actionEvent.getActionCommand(); | |
switch (action){ | |
case "Новый": | |
controller.createNewDocument(); | |
break; | |
case "Открыть": | |
controller.openDocument(); | |
break; | |
case"Сохранить": | |
controller.saveDocument(); | |
break; | |
case"Сохранить как...": | |
controller.saveDocumentAs(); | |
break; | |
case"Выход": | |
controller.exit(); | |
break; | |
case"О программе": | |
showAbout(); | |
break; | |
} | |
} | |
public void selectedTabChanged() { | |
int index= tabbedPane.getSelectedIndex(); | |
if (index==0){ | |
controller.setPlainText(plainTextPane.getText()); | |
} | |
if(index==1){ | |
plainTextPane.setText(controller.getPlainText()); | |
} | |
resetUndo(); | |
} | |
public boolean canUndo(){ | |
return undoManager.canUndo(); | |
} | |
public boolean canRedo(){ | |
return undoManager.canRedo(); | |
} | |
public void undo(){ | |
try { undoManager.undo(); | |
}catch (CannotUndoException e){ | |
ExceptionHandler.log(e); | |
} | |
} | |
public void redo(){ | |
try {undoManager.redo(); | |
}catch (CannotRedoException e){ | |
ExceptionHandler.log(e); | |
} | |
} | |
public void resetUndo(){undoManager.discardAllEdits();} | |
public UndoListener getUndoListener() { | |
return undoListener; | |
} | |
public boolean isHtmlTabSelected(){ | |
if(tabbedPane.getSelectedIndex()==0){return true;} | |
return false; | |
} | |
public void selectHtmlTab(){ | |
tabbedPane.setSelectedIndex(0); | |
resetUndo(); | |
} | |
public void update(){ | |
htmlTextPane.setDocument(controller.getDocument()); | |
} | |
public void showAbout(){ | |
JOptionPane optionPane = new JOptionPane(); | |
JOptionPane.showMessageDialog(optionPane,"Created soft!","Create by SHTABA09", JOptionPane.INFORMATION_MESSAGE); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
taskKey="com.javarush.task.task32.task3209.big24"\n\nHTML Editor (24) | |
Твой html редактор готов! | |
Ты научился: | |
- Создавать приложения с графическим интерфейсом. | |
- Работать с диалоговыми окнами. | |
- Пользоваться классами из библиотеки Swing. | |
- Реализовывать взаимодействие компонентов программы с помощью событий, слушателей, | |
действий. | |
- Усилил свои знания в области MVC. | |
Что можно улучшить в разработанном редакторе: | |
- Добавить панель инструментов, повторяющую функционал меню. | |
- Добавить подсветку html тегов на второй вкладке. | |
- Добавить возможность загрузки документа из Интернет. | |
- Расширить возможности редактора (вставка картинки, ссылки и т.д.) | |
Поздравляю, так держать! | |
Требования: | |
1. html редактор готов! | |
HTML Editor (23) | |
23.1. Напишем метод для сохранения открытого файла saveDocument(). Метод должен | |
работать также, как saveDocumentAs(), но не запрашивать файл у пользователя, а | |
использовать currentFile. Если currentFile равен null, то вызывать метод saveDocumentAs(). | |
23.2. Пришло время реализовать метод openDocument(). Метод должен работать | |
аналогично методу saveDocumentAs(), в той части, которая отвечает за выбор файла. | |
Подсказка: Обрати внимание на имя метода для показа диалогового окна. | |
Когда файл выбран, необходимо: | |
23.2.1. Установить новое значение currentFile. | |
23.2.2. Сбросить документ. | |
23.2.3. Установить имя файла в заголовок у представления. | |
23.2.4. Создать FileReader, используя currentFile. | |
23.2.5. Вычитать данные из FileReader-а в документ document с помощью объекта класса | |
HTMLEditorKit. | |
23.2.6. Сбросить правки (вызвать метод resetUndo представления). | |
23.2.7. Если возникнут исключения - залогируй их и не пробрасывай наружу. | |
Проверь работу пунктов меню Сохранить и Открыть. | |
HTML Editor (22) | |
Реализуем в контроллере метод для сохранения файла под новым именем saveDocumentAs(). | |
Реализация должна: | |
22.1. Переключать представление на html вкладку. | |
22.2. Создавать новый объект для выбора файла JFileChooser. | |
22.3. Устанавливать ему в качестве фильтра объект HTMLFileFilter. | |
22.4. Показывать диалоговое окно "Save File" для выбора файла. | |
22.5. Если пользователь подтвердит выбор файла: | |
22.5.1. Сохранять выбранный файл в поле currentFile. | |
22.5.2. Устанавливать имя файла в качестве заголовка окна представления. | |
22.5.3. Создавать FileWriter на базе currentFile. | |
22.5.4. Переписывать данные из документа document в объекта FileWriter-а аналогично тому, | |
как мы это делали в методе getPlainText(). | |
22.6. Метод не должен кидать исключения. | |
Проверь работу пункта меню Сохранить как... | |
HTML Editor (21) | |
Для открытия или сохранения файла мы будем использовать JFileChooser из библиотеки swing. | |
Объекты этого типа поддерживают фильтры, унаследованные от FileFilter. Сейчас мы напишем | |
свой фильтр: | |
21.1. Создай публичный класс HTMLFileFilter унаследованный от FileFilter. | |
21.2. Мы хотим, чтобы окно выбора файла отображало только html/htm файлы или папки. | |
Переопредели метод accept(File f), чтобы он возвращал true, если переданный файл | |
директория или содержит в конце имени ".html" или ".htm" без учета регистра. | |
21.3. Чтобы в окне выбора файла в описании доступных типов файлов отображался текст | |
"HTML и HTM файлы" переопредели соответствующим образом метод getDescription(). | |
HTML Editor (20) | |
20.1. Реализуй метод создания нового документа createNewDocument() в контроллере. Он | |
должен: | |
20.1.1. Выбирать html вкладку у представления. | |
20.1.2. Сбрасывать текущий документ. | |
20.1.3. Устанавливать новый заголовок окна, например: "HTML редактор". Воспользуйся | |
методом setTitle(), который унаследован в нашем представлении. | |
20.1.4. Сбрасывать правки в Undo менеджере. Используй метод resetUndo представления. | |
20.1.5. Обнулить переменную currentFile. | |
20.2. Реализуй метод инициализации init() контроллера. Он должен просто вызывать метод | |
создания нового документа. | |
Проверь работу пункта меню Новый. | |
HTML Editor (19) | |
Реализуем метод actionPerformed(ActionEvent actionEvent) у представления, этот метод | |
наследуется от интерфейса ActionListener и будет вызваться при выборе пунктов меню, у | |
которых наше представление указано в виде слушателя событий. | |
19.1. Получи из события команду с помощью метода getActionCommand(). Это будет | |
обычная строка. По этой строке ты можешь понять какой пункт меню создал данное | |
событие. | |
19.2. Если это команда "Новый", вызови у контроллера метод createNewDocument(). В этом | |
пункте и далее, если необходимого метода в контроллере еще нет - создай заглушки. | |
19.3. Если это команда "Открыть", вызови метод openDocument(). | |
19.4. Если "Сохранить", то вызови saveDocument(). | |
19.5. Если "Сохранить как..." - saveDocumentAs(). | |
19.6. Если "Выход" - exit(). | |
19.7. Если "О программе", то вызови метод showAbout() у представления. | |
Проверь, что заработали пункты меню Выход и О программе. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment