swing文本组件设置字体颜色TextPane

 

普通文本框和文本域设置不了字体颜色,需要用TextPane

文本窗格继承自编辑器窗格

public class JTextPane extends JEditorPane

 

样例:

MutableAttributeSet attrRed = new SimpleAttributeSet();
StyleConstants.setForeground(attrRed, Color.RED);
this.jTextPane1.getDocument().insertString(this.jTextPane1.getDocument().getEndPosition().getOffset()-1,"\n正在比较……\n",attrRed);

 

参考:

Swing对JTextPane中字体颜色的设置

http://www.blogjava.net/Swing/archive/2007/07/09/128965.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中设置字体颜色可以使用Java的Swing库中的JTextPane或JLabel组件。这些组件都提供了设置字体颜色的方法。 以下是使用JTextPane设置字体颜色的示例代码: ```java import javax.swing.*; import javax.swing.text.*; public class TextPaneDemo extends JFrame { public TextPaneDemo() { JTextPane textPane = new JTextPane(); StyledDocument doc = textPane.getStyledDocument(); Style style = textPane.addStyle("Color Style", null); StyleConstants.setForeground(style, Color.RED); try { doc.insertString(doc.getLength(), "Hello, World!", style); } catch (BadLocationException e) { e.printStackTrace(); } add(textPane); pack(); setVisible(true); } public static void main(String[] args) { new TextPaneDemo(); } } ``` 这个示例创建了一个JTextPane对象,并获取了它的StyledDocument对象。然后使用addStyle()方法创建了一个Style对象,命名为"Color Style"。接着使用StyleConstants类的setForeground()方法将字体颜色设置红色。最后,使用insertString()方法将文本插入到JTextPane中。 使用JLabel设置字体颜色的示例代码如下: ```java import javax.swing.*; import java.awt.*; public class LabelDemo extends JFrame { public LabelDemo() { JLabel label = new JLabel("Hello, World!"); label.setForeground(Color.RED); add(label); pack(); setVisible(true); } public static void main(String[] args) { new LabelDemo(); } } ``` 这个示例创建了一个JLabel对象,并使用setForeground()方法将字体颜色设置红色。然后将JLabel添加到JFrame中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值