java 设置字体的颜色_Java设置字体颜色

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值