使用Swing实现简易而不简单的文档编辑器
本文通过Swing来实现文档简易而不简单的文档编辑器,该文档编辑器的功能包括:
设置字体样式:粗体,斜体,下划线,可扩展设置字体:宋体,黑体,可扩展设置字号:12,14,18,20,30,40, 可扩展设置字体颜色:红色,蓝色,绿色,黄色,黑色,可扩展设置字体背景颜色:淡蓝,淡黄,淡绿,灰色,无色,可扩展插入图片效果如下所示:
public class DocImageAction extends StyledTextAction {private static final long serialVersionUID = 1L;public DocImageAction(String nm, JTextPane panl) {super(nm);this.panl = panl;}public void actionPerformed(ActionEvent e) {JFileChooser f = new JFileChooser(); // 查找文件f.showOpenDialog(null);System.out.println(f.getSelectedFile());ImageIcon icon = createImageIcon(f.getSelectedFile(), "a cute pig");JTextPane editor = this.panl;if (editor != null) {System.out.println("I am in here");StyledDocument doc = getStyledDocument(editor);editor.setCaretPosition(doc.getLength()); // 设置插入位置editor.insertIcon(icon); // 插入图片}}private JTextPane panl;/** Returns an ImageIcon, or null if the path was invalid. */protected static ImageIcon createImageIcon(String path, String description) {java.net.URL imgURL = DocImageAction.class.getResource(path);if (imgURL != null) {return new ImageIcon(imgURL, description);} else {System.err.println("Couldn't find file: " + path);return null;}}}