JTextArea更改下一个附加的背景颜色 [英] JTextArea change next append's background color

查看:906
本文介绍了JTextArea更改下一个附加的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户不可编辑的JTextArea。
它作为一个控制台,但没有输入。我想改变下一个追加的背景颜色,但不知道如何。我有一个想法:
$ b $ ol <

  • 创建一个Font类型的实例,并以某种方式设置该字体对象的背景颜色
  • 在调用下一个append之前调用方法JTextArea.setFont(之前创建的实例)。
  • 调用JTextArea.append(message with a background color \\\
    );

    我认为它可行,但我不知道如何为Font对象设置BackGroundColor属性。任何人都可以给我一些见解吗?谢谢。

    解决方案

    你不能使用JTextArea。它不支持不同的字体颜色。



    相反,您需要使用 JTextPane ,您可以使用attibutes 。下面是一个简单的例子,让你开始:

      import java.awt。*; 
    import java.awt.event。*;
    import javax.swing。*;
    import javax.swing.text。*;

    public class TextPaneAttributes extends JPanel
    {
    $ b $ public TextPaneAttributes()
    {
    setLayout(new BorderLayout());

    JTextPane textPane = new JTextPane();
    textPane.setText(one \\\
    two\\\
    three\\\
    four\\\
    five\\\
    six\\\
    seven\\\
    eight);

    // DefaultHighlighter highlighter =(DefaultHighlighter)textPane.getHighlighter();
    // highlighter.setDrawsLayeredHighlights(false);

    //定义一些字符和段落属性

    SimpleAttributeSet keyWord = new SimpleAttributeSet();
    StyleConstants.setBold(keyWord,true);

    SimpleAttributeSet green = new SimpleAttributeSet();
    StyleConstants.setForeground(green,Color.GREEN);

    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center,StyleConstants.ALIGN_CENTER);

    SimpleAttributeSet left = new SimpleAttributeSet();
    StyleConstants.setAlignment(left,StyleConstants.ALIGN_LEFT);

    //更改某些现有文本的属性

    StyledDocument doc = textPane.getStyledDocument();
    doc.setCharacterAttributes(0,3,keyWord,false);
    doc.setCharacterAttributes(8,5,green,true);
    doc.setParagraphAttributes(20,1,center,false);

    //添加一些带有属性的文本

    try
    {
    doc.insertString(doc.getLength(),\ nNormal text,空值);
    doc.insertString(doc.getLength(),\ nGreen text centered,green);
    doc.setParagraphAttributes(doc.getLength(),1,center,false);
    doc.insertString(doc.getLength(),\ nKeyword text,keyWord);
    doc.setParagraphAttributes(doc.getLength(),1,left,false);

    //文档末尾的新输入文本将继承
    //keyword属性,除非我们删除属性

    textPane.setCaretPosition(doc .getLength());
    textPane.getInputAttributes()。removeAttributes(keyWord);

    catch(Exception e){}
    $ b $ //添加文本框到框架

    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setPreferredSize(new Dimension(200,250));
    add(scrollPane);

    //创建一个按钮面板

    JPanel按钮= new JPanel();
    add(按钮,BorderLayout.PAGE_END);

    //添加一个粗体按钮

    JButton bold = new JButton(new StyledEditorKit.BoldAction());
    buttons.add(bold);

    //添加右对齐按钮

    JButton right = new JButton(new StyledEditorKit.AlignmentAction(Align Right,StyleConstants.ALIGN_RIGHT));
    buttons.add(right);


    private static void createAndShowGUI()
    {
    JFrame frame = new JFrame(SSCCE);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TextPaneAttributes());
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);

    $ b $ public static void main(String [] args)
    {
    EventQueue.invokeLater(() - > createAndShowGUI());
    $ * b $ b EventQueue.invokeLater(new Runnable()
    {
    public void run()
    {
    createAndShowGUI();
    }
    });
    * /
    }
    }

    我会让你请阅读 StyleConstants API以了解您可以控制的其他属性,包括文本的背景颜色。您可以为每个属性集设置多个属性。



    阅读 Text Component Features 获取更多信息和工作示例。


    I have a JTextArea which is not user editable. It acts as a console but without input. I want to change the background color for the next append only but have no idea how. I have an idea:

    1. Create an instance of type Font and somehow set the background color of this font object
    2. Call the method JTextArea.setFont(the instance i previously created) right before i call my next append.
    3. call JTextArea.append("message with a background color\n");

    I think it works but I have no idea how to set the BackGroundColor attribute for a Font Object. Can anyone give me some insight please? Thanks.

    解决方案

    You can't use a JTextArea. It doesn't support different font colors.

    Instead you need to use a JTextPane and you can play with attibutes. Here is a simple example to get you started:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class TextPaneAttributes extends JPanel
    {
    
        public TextPaneAttributes()
        {
            setLayout( new BorderLayout() );
    
            JTextPane textPane = new JTextPane();
            textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );
    
    //      DefaultHighlighter highlighter =  (DefaultHighlighter)textPane.getHighlighter();
    //      highlighter.setDrawsLayeredHighlights(false);
    
            //  Define some character and paragraph attributes
    
            SimpleAttributeSet keyWord = new SimpleAttributeSet();
            StyleConstants.setBold(keyWord, true);
    
            SimpleAttributeSet green = new SimpleAttributeSet();
            StyleConstants.setForeground(green, Color.GREEN);
    
            SimpleAttributeSet center = new SimpleAttributeSet();
            StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    
            SimpleAttributeSet left = new SimpleAttributeSet();
            StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
    
            //  Change attributes on some existing text
    
            StyledDocument doc = textPane.getStyledDocument();
            doc.setCharacterAttributes(0, 3, keyWord, false);
            doc.setCharacterAttributes(8, 5, green, true);
            doc.setParagraphAttributes(20, 1 , center, false);
    
            //  Add some text with attributes
    
            try
            {
                doc.insertString(doc.getLength(), "\nNormal text", null);
                doc.insertString(doc.getLength(), "\nGreen text centered", green);
                doc.setParagraphAttributes(doc.getLength(), 1 , center, false);
                doc.insertString(doc.getLength(), "\nKeyword text", keyWord);
                doc.setParagraphAttributes(doc.getLength(), 1 , left, false);
    
                //  Newly typed text at the end of the document will inherit the
                //  "keyword" attributes unless we remove the attributes
    
                textPane.setCaretPosition(doc.getLength());
                textPane.getInputAttributes().removeAttributes(keyWord);
            }
            catch(Exception e) {}
    
            //  Add text pane to frame
    
            JScrollPane scrollPane = new JScrollPane( textPane );
            scrollPane.setPreferredSize( new Dimension( 200, 250 ) );
            add( scrollPane );
    
            //  Create a Button panel
    
            JPanel buttons = new JPanel();
            add(buttons, BorderLayout.PAGE_END);
    
            //  Add a Bold button
    
            JButton bold = new JButton( new StyledEditorKit.BoldAction() );
            buttons.add( bold );
    
            //  Add Right Alignment button
    
            JButton right = new JButton( new StyledEditorKit.AlignmentAction("Align Right", StyleConstants.ALIGN_RIGHT) );
            buttons.add( right );
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new TextPaneAttributes());
            frame.pack();
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater( () -> createAndShowGUI() );
    /*
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });
    */
        }
    }
    

    I'll let you read the StyleConstants API for other properties you can control including the background color of the text. You can set multiple properties for each attribute set.

    Read the section from the Swing tutorial on Text Component Features for more information and working examples.

    这篇关于JTextArea更改下一个附加的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆