jtextpane html 超链接 字体
1) 设置 html的 B 属性
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setBold(attrset, true);
app.getJtp_html().setCharacterAttributes(attrset, false); // 会将选取中的文本设置为粗体
2) 设置 html的 I 或 EM 属性
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setItalic(attrset, true);
app.getJtp_html().setCharacterAttributes(attrset, false);
3) 设置选取中的文本的颜色
JColorChooser jcc = new JColorChooser(); //对话框
Color c = jcc.showDialog(app.getJContentPane(), "请选择颜色", Color.black);
if(c != null) {
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setForeground(attrset, c);
app.getJtp_html().setCharacterAttributes(attrset, false);
}
4) 给选取中文字添加超链接
用 HTMLEditorKit 插入html标签,用这个的话要注意在开始的时候给 jTextPane注入一个new HTMLEditorKit(), 不然会出错
String link = javax.swing.JOptionPane.showInputDialog(app.getJContentPane(), "请输入链接地址:");
if(link == null (link != null && link.trim().length() == 0))
return ;
HTMLEditorKit hek = (HTMLEditorKit) app.getJtp_html().getEditorKit();
try {
String t = app.getJtp_html().getSelectedText();
app.getJtp_html().getDocument().remove(app.getJtp_html().getCaretPosition(), t.length());
hek.insertHTML((HTMLDocument) app.getJtp_html().getDocument(), app.getJtp_html().getCaretPosition(), "<a href="'">").concat(t).concat("</a>"), 0, 0, HTML.Tag.A);
} catch(Exception ex) {
ex.printStackTrace();
}
5) 对齐方式, 左,中,右
final Style style = getJtp_html().addStyle("div", null);
void insertStyle(MutableAttributeSet tmpStyle) {
//StyleConstants.setAlignment(tmpStyle, StyleConstants.ALIGN_LEFT);
try { getJtp_html().setParagraphAttributes(tmpStyle, false); }
catch(Exception ex) {
// 一定要这句, 上面的try会现exception,使得界面没有更新,用这个方法就可以
getJtp_html().setText(getJtp_html().getText());
}
}
左: StyleConstants.setAlignment(app.style, StyleConstants.ALIGN_LEFT);
app.insertStyle(app.style);
右,中同理
6) 添加 UL 或 OL , LI 功能, 自动编号
Style s1 = app.getJtp_html().getStyle("ul");
if(s1 == null)
s1 = app.getJtp_html().addStyle("ul", null);
Style s2 = app.getJtp_html().addStyle("li", s1);
app.insertStyle(s2);
7) 去掉选取中的文字
String t = app.getJtp_html().getSelectedText();
try { app.getJtp_html().getDocument().remove(app.getJtp_html().getSelectionStart(), t.length()); }
catch(Exception ex) { ex.printStackTrace(); }
8) 设置字体
要用到一个 JcomboBox,这里不列出来, jcb为JComboBox
jcb.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent e) {
if(e.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
String s = e.getItem().toString(); //字体名称
if(s != null && s.trim().length() > 0) {
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setFontFamily(attrset, s);
app.getJtp_html().setCharacterAttributes(attrset, false);
}
}
}
});
9) 设置字体大小
同理,使用
StyleConstants.setFontSize(attrset, s);
相关文章:
JTextPane的简单的html可视编辑器2-源码编辑
JTextPane的简单的html可视编辑器3-源码下载
Labels:
Trackback: http://cwq.iou1314.com/_a156
Trackback: http://cwq.iou1314.com/_a156




















