栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java如何在JTextArea中更改文本颜色?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java如何在JTextArea中更改文本颜色?

Jtextarea
是为了娱乐
Plain Text
。应用于单个字符的设置适用于中的整个文档
Jtextarea
。但随着
JTextPane
JEditorPane
你有选择,而影响了你
String Literals
按照自己的喜好。在
JTextPane
的帮助下,您可以这样操作:

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.text.AttributeSet;import javax.swing.text.SimpleAttributeSet;import javax.swing.text.StyleConstants;import javax.swing.text.StyleContext;public class TextPaneTest extends Jframe{    private JPanel topPanel;    private JTextPane tPane;    public TextPaneTest()    {        topPanel = new JPanel();     setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);        setLocationRelativeTo(null);         EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));        tPane = new JTextPane();  tPane.setBorder(eb);        //tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));        tPane.setMargin(new Insets(5, 5, 5, 5));        topPanel.add(tPane);        appendToPane(tPane, "My Name is Too Good.n", Color.RED);        appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.BLUE);        appendToPane(tPane, "Stack", Color.DARK_GRAY);        appendToPane(tPane, "Over", Color.MAGENTA);        appendToPane(tPane, "flow", Color.ORANGE);        getContentPane().add(topPanel);        pack();        setVisible(true);       }    private void appendToPane(JTextPane tp, String msg, Color c)    {        StyleContext sc = StyleContext.getDefaultStyleContext();        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);        int len = tp.getdocument().getLength();        tp.setCaretPosition(len);        tp.setCharacterAttributes(aset, false);        tp.replaceSelection(msg);    }    public static void main(String... args)    {        SwingUtilities.invokeLater(new Runnable() {     public void run()     {         new TextPaneTest();     } });    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495295.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号