java文本框的内容改变颜色_关于在java文本框类型组件改变字体颜色

1.由于java可视化常用的文本框组件,比如JTextArea,JTextField属于纯文本类型,类似于电脑中的txt文本文件,最多可以设置字体的格式和大小,不能改变字体颜色,所以这就需要另外一种叫做JTextPane的组件

简单源码如下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();

SimpleAttributeSet attr2=new SimpleAttributeSet();

StyleConstants.setForeground(attr, Color.red);

StyleConstants.setForeground(attr2, Color.blue);

d.insertString(d.getLength(),"红色",attr);

d.insertString(d.getLength(),"红色",attr2);

this.add(text);

this.setSize(200,200);

this.setVisible(true);

}

}最终通过静态的setForeground方法进行颜色的设置

b87b71b3c499b51043565b5688fc1154.png

该方法需要的第一个参数为一个接口,它的一个实现类是

SimpleAttributeSet,所以可以通过上文中的代码实现对字体颜色的操作

运行结果如下

b0a45e93226635523c124c3c2d1943e2.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值