Swing/HTMLEditorKit のバックアップ(No.13)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/HTMLEditorKit へ行く。
- 1 (2014-09-17 (水) 02:29:52)
- 2 (2014-10-22 (水) 00:54:13)
- 3 (2015-02-18 (水) 15:04:37)
- 4 (2016-12-16 (金) 14:20:09)
- 5 (2017-03-28 (火) 15:13:30)
- 6 (2017-04-07 (金) 13:51:51)
- 7 (2018-02-07 (水) 18:33:20)
- 8 (2019-11-27 (水) 13:50:42)
- 9 (2021-06-03 (木) 09:47:18)
- 10 (2025-01-03 (金) 08:57:02)
- 11 (2025-01-03 (金) 09:01:23)
- 12 (2025-01-03 (金) 09:02:38)
- 13 (2025-01-03 (金) 09:03:21)
- 14 (2025-01-03 (金) 09:04:02)
- category: swing
folder: HTMLEditorKit
title: JTextPaneで修飾したテキストをJTextAreaにHtmlソースとして表示する
tags: [JTextPane, HTMLEditorKit, Html, JPopupMenu, JTextArea, JTabbedPane, ChangeListener]
author: aterai
pubdate: 2013-04-01T00:08:05+09:00
description: HTMLEditorKitを使用するJTextPaneで修飾したテキストをJTextAreaにHtmlソースとして表示、編集、JTextPaneに反映するテストを行なっています。
image:
Summary
HTMLEditorKit
を使用するJTextPane
で修飾したテキストをJTextArea
にHtml
ソースとして表示、編集、JTextPane
に反映するテストを行なっています。
Screenshot

Advertisement
Source Code Examples
textPane.setComponentPopupMenu(new HTMLColorPopupMenu());
// textPane.setEditorKit(new HTMLEditorKit());
textPane.setContentType("text/html");
textArea.setText(textPane.getText());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("JTextPane", new JScrollPane(textPane));
tabbedPane.addTab("JTextArea", new JScrollPane(textArea));
tabbedPane.addChangeListener(new ChangeListener() {
@Override public void stateChanged(ChangeEvent e) {
JTabbedPane t = (JTabbedPane) e.getSource();
int i = t.getSelectedIndex();
try {
if (i == 0) {
textPane.setText(textArea.getText());
} else {
String str = textPane.getText();
textArea.setText(str);
}
} catch (Exception ex) {
ex.printStackTrace();
}
t.revalidate();
}
});
View in GitHub: Java, KotlinExplanation
HTMLEditorKit
を使用(コンテンツ形式をtext/html
に設定)するJTextPane
でJEditorPane#getText()
を実行すると、HTMLEditorKit
から文字色などのStyle
を設定したHtml
ソースとして文字列を取得可能なので、JTabbedPane
がJTextArea
に切り替わるときにJTextArea
に流し込んでいます。
逆に、JTextArea
でHtml
ソースを編集してJTabbedPane
でJTextPane
に切り替える時には、JEditorPane#setText(String)
内でHTMLEditorKit
にHTML
形式で読み込まれるよう設定しています。
textPane.setContentType("text/html");
とコンテンツ形式を設定しておかないとJEditorPane#setText(String)
でDocument
が更新されない場合がある?- この場合以下のように
textPane.setText(textArea.getText());
ではなくHTMLEditorKit#insertHTML(...)
を使用する// textPane.setText(textArea.getText()); textPane.setText(""); HTMLEditorKit hek = (HTMLEditorKit) textPane.getEditorKit(); HTMLDocument doc = (HTMLDocument) textPane.getStyledDocument(); hek.insertHTML(doc, 0, textArea.getText(), 0, 0, null);
HTMLEditorKit
からHTML Tag
を取り除いた文字列を取得するサンプル
// import java.io.StringReader;
// import javax.swing.text.html.parser.*;
ParserDelegator delegator = new ParserDelegator();
StringBuffer s = new StringBuffer();
delegator.parse(new StringReader(str), new HTMLEditorKit.ParserCallback() {
@Override public void handleText(char[] text, int pos) {
s.append(text);
}
}, Boolean.TRUE);
System.out.println(s.toString());