在JTextPane(Java Swing)中更改段落的背景颜色 [英] Changing the background color of a paragraph in JTextPane (Java Swing)

查看:305
本文介绍了在JTextPane(Java Swing)中更改段落的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Java Swing中更改段落的背景颜色?我试图使用setParagraphAttributes方法(代码如下)设置它,但似乎不工作。

Is it possible to change the background color of a paragraph in Java Swing? I tried to set it using the setParagraphAttributes method (code below) but doesn't seem to work.

    StyledDocument doc = textPanel.getStyledDocument();
    Style style = textPanel.addStyle("Hightlight background", null);
    StyleConstants.setBackground(style, Color.red);

    Style logicalStyle = textPanel.getLogicalStyle();
    doc.setParagraphAttributes(textPanel.getSelectionStart(), 1, textPanel.getStyle("Hightlight background"), true);
    textPanel.setLogicalStyle(logicalStyle);


推荐答案

UPDATE:
我刚刚发现了一个类叫Highlighter.I不认为你应该使用setbackground风格。请改用DefaultHighlighter类。

UPDATE: I just found out about a class called Highlighter.I dont think you should be using the setbackground style. Use the DefaultHighlighter class instead.

Highlighter h = textPanel.getHighlighter();
h.addHighlight(1, 10, new DefaultHighlighter.DefaultHighlightPainter(
            Color.red));

addHighlight方法的前两个参数只是文本的起始索引和结束索引想突出。您可以多次调用此方法以突出显示不连续的文本行。

The first two parameters of the addHighlight method are nothing but the starting index and ending index of the text you want to highlight. You can call this method multiple timesto highlight discontinuous lines of text.

老问答:

我不知道为什么setParagraphAttributes方法似乎无效。但这样做似乎工作。

I have no idea why the setParagraphAttributes method doesnt seem to work. But doing this seems to work.

    doc.insertString(0, "Hello World", textPanel.getStyle("Hightlight background"));

也许你现在可以为此做一个黑客...

Maybe you can work a hack around this for now...

这篇关于在JTextPane(Java Swing)中更改段落的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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