码迷,mamicode.com
首页 > 其他好文 > 详细

设置字体颜色

时间:2017-08-18 12:31:42      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:etc   tchar   private   tcl   ati   constant   oid   extends   red   

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import java.awt.*;

/**
 * Created by ai on 17/8/18.
 */
public class TextPaneTest extends JFrame {

    private JPanel topPanel;
    private JTextPane tPane;

    public TextPaneTest() {
        topPanel = new JPanel();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        tPane = new JTextPane();
        tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        tPane.setMargin(new Insets(5, 5, 5, 5));

        topPanel.add(tPane);

        appendToPane(tPane, "这里是红色\n", Color.RED);
        appendToPane(tPane, "蓝色的字 ", Color.BLUE);
        appendToPane(tPane, "我猜", Color.DARK_GRAY);
        appendToPane(tPane, "我再猜", Color.MAGENTA);
        appendToPane(tPane, "我猜猜猜", Color.ORANGE);

        add(topPanel);
        pack();
        setVisible(true);
    }

    private void appendToPane(JTextPane tp, String msg, Color c) {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "宋体");
        aset = sc.addAttribute(aset, StyleConstants.Alignment,
                StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.replaceSelection(msg);
    }

    public static void main(String[] args) {
        new TextPaneTest();
    }
}

  

设置字体颜色

标签:etc   tchar   private   tcl   ati   constant   oid   extends   red   

原文地址:http://www.cnblogs.com/dreammyone/p/7388864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!