JDocumentEditor
package infonode;
/**
*
* @author sony
*/
//JDocumentEditor.java
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.undo.*;
public class JDocumentEditor extends JTextPane {
UndoHandler uh = null;
Font myFont;
javax.swing.plaf.FontUIResource f;
public JDocumentEditor() {
this.setContentType("text/html");
this.setFont(new Font("arial", 0, 14));
this.setText("hey i am deepak");
this.setDragEnabled(true);
}
public void setTextForeground(Color c) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setForeground(att, c);
this.setCharacterAttributes(att, false);
}
public void setTextBackground(Color c) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setBackground(att, c);
this.setCharacterAttributes(att, false);
}
public void setTextBold() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setBold(att, !StyleConstants.isBold(att));
this.setCharacterAttributes(att, false);
System.out.println(this.getSelectedText());
}
public void setTextItalic() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setItalic(att, !StyleConstants.isItalic(att));
this.setCharacterAttributes(att, false);
}
public void setTextUnderline() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setUnderline(att, !StyleConstants.isUnderline(att));
this.setCharacterAttributes(att, false);
}
public void setTextStrikeThrough() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setStrikeThrough(att, !StyleConstants.isStrikeThrough(att));
this.setCharacterAttributes(att, false);
}
public void setTextSuperscript() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setSuperscript(att, !StyleConstants.isSuperscript(att));
this.setCharacterAttributes(att, false);
}
public void setTextSubscript() {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
StyleConstants.setSubscript(att, !StyleConstants.isSubscript(att));
this.setCharacterAttributes(att, false);
}
public void setfonts() {
try {
EditorKit styleEd = this.getEditorKit();
if (!(styleEd instanceof StyledEditorKit)) {
return;
}
MutableAttributeSet att = ((StyledEditorKit) styleEd).getInputAttributes();
File fontFile = new File("C://Users//sony//Desktop//1131.ttf");
myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);
System.out.println(this.getFont());
f = new javax.swing.plaf.FontUIResource(myFont);
System.out.println(f.getFontName());
this.setFont(myFont);
this.setFont(f);
System.out.println(this.getFont());
this.setCharacterAttributes(att, false);
} catch (FontFormatException ex) {
Logger.getLogger(JDocumentEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JDocumentEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setTextFontFamily(String fnt) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setFontFamily(att, fnt);
this.setCharacterAttributes(att, false);
}
public void setTextFontSize(int size) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setFontSize(att, size);
this.setCharacterAttributes(att, false);
}
public void setTextAlignment(int align) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setAlignment(att, align);
this.setParagraphAttributes(att, false);
}
public void setTextIndent(float indent) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setFirstLineIndent(att, indent);
this.setParagraphAttributes(att, false);
}
public void setTextSpaceAbove(float space) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setSpaceAbove(att, space);
this.setParagraphAttributes(att, false);
}
public void setTextSpaceBelow(float space) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setSpaceBelow(att, space);
this.setParagraphAttributes(att, false);
}
public void setTextLineSpacing(float space) {
MutableAttributeSet att = new SimpleAttributeSet();
StyleConstants.setLineSpacing(att, space);
this.setParagraphAttributes(att, false);
}
public void insertHTML(String s) {
try {
((HTMLEditorKit) this.getEditorKit()).read(new java.io.StringReader(s), this.getDocument(), this.getSelectionStart());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void insertImage(String file) {
try {
((HTMLEditorKit) this.getEditorKit()).read(new java.io.StringReader("<img src=\"" + file + "\" />"), this.getDocument(), this.getSelectionStart());
ImageIcon imgicon = new ImageIcon(file);
this.insertIcon(imgicon);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void insertTable(int r, int c) {
try {
StringBuilder sb = new StringBuilder("<table border=1>\n");
for (int i = 0; i < r; i++) {
sb.append("<tr>");
for (int j = 0; j < c; j++) {
sb.append("<td></td>");
}
sb.append("</tr>\n");
}
sb.append("</table>");
((HTMLEditorKit) this.getEditorKit()).read(new java.io.StringReader(sb.toString()), this.getDocument(), this.getSelectionStart());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setUndoRedo(AbstractButton undo, AbstractButton redo) {
this.getDocument().addUndoableEditListener(uh = new UndoHandler(undo, redo));
}
public void undo() {
uh.reverseEditing(false);
}
public void redo() {
uh.reverseEditing(true);
}
public void resetUndo() {
uh.resetUndo();
}
class UndoHandler implements UndoableEditListener, ActionListener {
private UndoManager um = null;
private AbstractButton undo = null, redo = null;
public UndoHandler(AbstractButton umi, AbstractButton rmi) {
um = new UndoManager();
undo = umi;
redo = rmi;
JDocumentEditor.this.getDocument().addUndoableEditListener(this);
undo.addActionListener(this);
redo.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
reverseEditing(ae.getSource() == redo);
}
public void reverseEditing(boolean r) {
try {
if (r) {
um.redo();
} else {
um.undo();
}
refreshState();
} catch (Exception ex) {
javax.swing.JOptionPane.showMessageDialog(null,
"Error in " + (r ? "redo " : "undo ") + ex.toString());
}
}
public void resetUndo() {
um.discardAllEdits();
undo.setEnabled(false);
redo.setEnabled(false);
JDocumentEditor.this.getDocument().addUndoableEditListener(this);
}
public void refreshState() {
undo.setEnabled(um.canUndo());
redo.setEnabled(um.canRedo());
undo.setText(undo.isEnabled() ? um.getUndoPresentationName() : "Undo");
redo.setText(undo.isEnabled() ? um.getRedoPresentationName() : "Redo");
}
public void undoableEditHappened(UndoableEditEvent uee) {
try {
um.addEdit(uee.getEdit());
this.refreshState();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String a[]) {
new JDocumentEditor();
JFrame jf = new JFrame();
jf.setVisible(true);
JButton jb1 = new JButton("bold");
final JTextField jfield = new JTextField(" ");
jf.add(jfield);
jf.add(jb1);
jf.setLayout(new FlowLayout());
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(jfield.getText());
}
});
}
}
package infonode;
/**
*
* @author sony
*/
//DocumentTest.java
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.text.*;
class DocumentTest extends JFrame implements ActionListener {
Font myFont = null;
JDocumentEditor ed = new JDocumentEditor();
JFileChooser fc = new JFileChooser(), img = new JFileChooser();
public DocumentTest() {
super("Document Editor");
createToolbar();
this.getContentPane().add(new JScrollPane(ed), "Center");
fc.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(java.io.File f) {
String t = f.getName().toLowerCase();
return f.isDirectory() || t.endsWith(".html");
}
public String getDescription() {
return "HTML";
}
});
img.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(java.io.File f) {
String t = f.getName().toLowerCase();
return f.isDirectory() || t.endsWith(".jpg") || t.endsWith(".jpeg") || t.endsWith(".png") || t.endsWith(".gif");
}
public String getDescription() {
return "Image Files";
}
});
ed.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
ed.insertHTML("<p> </p>");
}
}
});
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
ed.requestFocus();
}
private void createToolbar() {
JToolBar tool = new JToolBar();
String buttonName[] = {"New", "Open", "Save", "Font", "Size", "Left", "Center", "Right", "Above", "Below", "Indent", "Line Space", "Font Colour", "Background", "Bold", "Italic", "Underline", "Superscript", "Subscript", "Strike", "Image", "Table", "Print", "Gujarati"};
JButton temp = null;
JPanel p = new JPanel(new java.awt.GridLayout(4, 6));
for (int i = 0; i < buttonName.length; i++) {
temp = new JButton(buttonName[i]);
temp.addActionListener(this);
p.add(temp);
}
JButton undo = new JButton("Undo"), redo = new JButton("Redo");
ed.setUndoRedo(undo, redo);
p.add(undo);
tool.add(p);
this.getContentPane().add(tool, "North");
}
public void actionPerformed(ActionEvent ae) {
String com = ae.getActionCommand();
if (com.equals("Font")) {
ed.setTextFontFamily(JOptionPane.showInputDialog(this, "Enter Font Name"));
} else if (com.equals("Size")) {
ed.setTextFontSize(Integer.parseInt(JOptionPane.showInputDialog(this, "Enter font size")));
} else if (com.equals("Gujarati")) {
ed.setfonts();
} else if (com.equals("Left")) {
ed.setTextAlignment(StyleConstants.ALIGN_LEFT);
} else if (com.equals("Center")) {
ed.setTextAlignment(StyleConstants.ALIGN_CENTER);
} else if (com.equals("Right")) {
ed.setTextAlignment(StyleConstants.ALIGN_RIGHT);
} else if (com.equals("Above")) {
ed.setTextSpaceAbove(Float.parseFloat(JOptionPane.showInputDialog(this, "Enter space above")));
} else if (com.equals("Below")) {
ed.setTextSpaceBelow(Float.parseFloat(JOptionPane.showInputDialog(this, "Enter space below")));
} else if (com.equals("Indent")) {
ed.setTextIndent(Float.parseFloat(JOptionPane.showInputDialog(this, "Enter first line indent")));
} else if (com.equals("Line Space")) {
ed.setTextLineSpacing(Float.parseFloat(JOptionPane.showInputDialog(this, "Enter line spacing")));
} else if (com.equals("Font Colour")) {
ed.setTextForeground(JColorChooser.showDialog(this, "Font colour", null));
} else if (com.equals("Background")) {
ed.setTextBackground(JColorChooser.showDialog(this, "Background", null));
} else if (com.equals("Bold")) {
ed.setTextBold();
} else if (com.equals("Italic")) {
ed.setTextItalic();
} else if (com.equals("Underline")) {
ed.setTextUnderline();
} else if (com.equals("Superscript")) {
ed.setTextSuperscript();
} else if (com.equals("Subscript")) {
ed.setTextSubscript();
} else if (com.equals("Strike")) {
ed.setTextStrikeThrough();
} else if (com.equals("New")) {
ed.setDocument(((javax.swing.text.html.HTMLEditorKit) ed.getEditorKit()).createDefaultDocument());
ed.resetUndo();
} else if (com.equals("Save")) {
saveFile();
} else if (com.equals("Open")) {
openFile();
ed.resetUndo();
} else if (com.equals("Image")) {
if (img.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
ed.insertImage(img.getSelectedFile().getAbsolutePath());
}
} else if (com.equals("Table")) {
ed.insertTable(Integer.parseInt(JOptionPane.showInputDialog(this, "Enter rows")), Integer.parseInt(JOptionPane.showInputDialog(this, "Enter columns")));
} else if (com.equals("Print")) {
try {
ed.print();
} catch (Exception ex) {
}
}
ed.requestFocus();
System.out.println(ed.getSelectedText() + ed.getText());
}
private void saveFile() {
if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
return;
}
java.io.File f = fc.getSelectedFile();
try {
java.io.FileWriter fw = new java.io.FileWriter(f);
ed.write(fw);
fw.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.toString());
}
}
private void openFile() {
ed.setEditable(false);
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
return;
}
java.io.File f = fc.getSelectedFile();
try {
ed.read(new java.io.FileReader(f), null);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.toString());
}
}
public static void main(String arg[]) {
DocumentTest dt = new DocumentTest();
}
}
随机推荐
- vue打包后dist的使用
发现问题 vue项目完成打包出dist后准备打开index.html,发现居然页面是一片空白,f12一片报红. 分析问题 经过多次网上查询后发现这是由于vue打包时,脚手架会帮你配置好大量参数,但其中 ...
- 推荐一款流量录制回放工具:jvm-sandbox-repeater
在软件开发和测试过程中,我们经常会遇到需要对网络请求进行录制和回放的需求,以便进行调试.测试和分析.为了模拟真实的用户请求,我们通常会使用各种流量录制回放工具来记录并重放网络请求. 其中,jvm-sa ...
- Yarn 3.0 Plug'n'Play (PnP) 安装和迁移
前言 以前用 npm, 后来 yarn 火了就用 yarn. 后来 yarn 2.0 大改版, Angular 不支持就一直没用. 一直到去年的 Angular 13 才开始支持. 最近又开始写 An ...
- 关于HOJ的搭建和二开经验小结
经验在最后,先说流程. 除了HOJ,之前先装的HDU,属实难用,然后是hustOJ,嗯很好用,但架不住丑,对管理员实在不友好. 好了不闲记,进入正题: 一.流程 1.官网文档先过一遍. 2.配置好do ...
- JavaScript——事件监听
事件监听 1.事件绑定 2.常见事件
- [namespace hdk] 向量 direct_vector
我忏悔我有罪我心情又不好了不知道干什么所以又不小心封了个东西啊啊啊啊啊啊啊啊 功能 已重载 [] 运算符(左值) 已重载 = 运算符(可使用向量或 std:::vector) 已重载 + += - - ...
- SXYZ-7.4训练赛
今天这场比赛把人心态考崩溃了,只考100分钟,四道思考和算法题,旁边大佬开局5分钟秒T1,我30分钟打了个T1暴力.┭┮﹏┭┮,呜呜~.T2,T4根据题意暴力.T3人手模拟了一下,完全没有任何思路,放 ...
- callable类型 是什么?
在 C++ 中,callable 类型(可调用类型)是指可以像函数一样被调用的对象 C++ 中有多种不同的可调用对象类型,它们可以通过函数调用运算符 () 被调用. 常见的 callable 类型包括 ...
- composer 执行脚本时报错:Error: You made a reference to a non-existent script @php artisan package:discover
composer 执行脚本时报错:Error: You made a reference to a non-existent script @php artisan package:discover. ...
- 使用BPF之前和之后生成直方图过程的对比
以bitehist为例: 使用BPF之前: 1.在内核中:开启磁盘IO事件的插桩观测. 2.在内核中,针对每个事件:向perf缓冲区写入一条记录.如果使用了跟踪点技术(推荐方式),记录中会包含关于磁盘 ...