JTextPaneを使う
package color;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame {
public static void main(String[] args) {
TextPaneTest test = new TextPaneTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
TextPaneTest() {
setTitle("TextPaneTest Test");
setBounds(10, 10, 300, 200);
JTextPane textPane = new JTextPane();
JScrollPane scroll = new JScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(scroll);
StyleContext sc = new StyleContext();
DefaultStyledDocument doc = new DefaultStyledDocument(sc);
textPane.setDocument(doc);
try {
doc.insertString(0, new String("太字で赤にスタイルを変更"), sc.getStyle(StyleContext.DEFAULT_STYLE));
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setBold(attr, true);
StyleConstants.setForeground(attr, Color.red);
// 引数1の文字目から引数2の文字分だけスタイルを変更する
doc.setCharacterAttributes(0, 4, attr, false);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}