java swing 文本域中改变字体颜色

我们常用的JTextArea是纯文本组件,不能改变字体的颜色,可以用JTextPane组件,它要比JTextArea功能强大很多,JTextPane的用法可以看java文档:点击打开链接

1.用JTextPane的setForeground设置字体颜色。

package java;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
public class W8_2_2 extends JFrame{
    public static void main(String[] args)
    {
    	new W8_2_2();
    }
    public W8_2_2()
    {
    	JTextPane text=new JTextPane();
    	text.setForeground(Color.BLUE);
    	this.add(text);
    	this.setSize(200,200);
    	this.setVisible(true);
    }
}

2.StyledDocument中设置字体颜色。

package java;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class W8_2_2 extends JFrame{
    public static void main(String[] args) throws BadLocationException
    {
    	new W8_2_2();
    }
    public W8_2_2() throws BadLocationException
    {
    	JTextPane text=new JTextPane();
    	StyledDocument d=text.getStyledDocument();
    	SimpleAttributeSet attr = new SimpleAttributeSet();
    	StyleConstants.setForeground(attr, Color.red);
    	d.insertString(d.getLength(),"红色",attr);
    	this.add(text);
    	this.setSize(200,200);
    	this.setVisible(true);
    }
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值