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); } }
相关文章推荐
- java8 Lambda表达式
- 安卓开发之java基础笔记【4】
- list集合
- java泛型之泛型边界
- ExtJS5 +Spring MVC CRUD
- Java序列化之关于Serializable的解释
- SpringData 学习(6)—— 学习 Repository 接口的第 1 个子接口 CRUDRepository
- 冒泡排序
- eclipse中要让一个 Java 源文件打开时编码格式为 UTF-8
- JAVA技术发展——你不知道的J2SE(四)
- Spark-Avro学习8之Java Avro使用(不生成code方式)
- Java中final关键字的用法
- 安卓开发之java基础笔记【3】
- spring路径通配符
- 码农小汪-Spring MVC-强大的数据绑定1
- 用Java写解谜Rpg-4.加载界面,RPG界面与Player
- 【第四章】 资源 之 4.4 Resource通配符路径 ——跟我学spring3
- java 调用 sqlite
- Java 多线程(七)——线程组与线程池
- 解决Setting property 'source' to 'org.eclipse.jst.jee.server的问题