您的位置:首页 > 编程语言 > Java开发

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

2016-05-02 15:42 615 查看

我们常用的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);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: