关于在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方法进行颜色的设置


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

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

运行结果如下


猜你喜欢

转载自blog.csdn.net/qq_36437446/article/details/79650191
今日推荐