2

Hi I am trying to find out whether it is possible to apply background color only to a portion of JTextpane? For example if I have a JTextpane of size 300 X 400 then can I apply some color to a portion 300 X 200 ?

I am not posting any code as I dont have any.

Eg: enter image description here

4

1 回答 1

2

您只需添加StyleConstants.Background, 作为 的参数addAttribute()StyleContext这将返回一个AttributeSet对象。希望这是你要找的:

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, Color.WHITE);
        appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.WHITE, Color.BLUE);
        appendToPane(tPane, "Stack", Color.DARK_GRAY, Color.BLACK);
        appendToPane(tPane, "Over", Color.MAGENTA, Color.BLUE);
        appendToPane(tPane, "flow", Color.ORANGE, Color.YELLOW);

        getContentPane().add(topPanel);

        pack();
        setVisible(true);   
    }

    private void appendToPane(JTextPane tp, String msg, Color f, Color b)
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, f);
        aset = sc.addAttribute(aset, StyleConstants.Background, b);

        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();
                }
            });
    }
}

这是输出:

文本窗格

于 2013-03-31T11:02:16.913 回答