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

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

问题描述

是否有可能改变Java Swing的一个段落的背景颜色?我尝试使用setParagraphAttributes法(code以下)来设置,但似乎并没有工作。

  StyledDocument中的DOC = textPanel.getStyledDocument();
    款式风格= textPanel.addStyle(Hightlight背景,NULL);
    StyleConstants.setBackground(风格,Color.red);    样式logicalStyle = textPanel.getLogicalStyle();
    doc.setParagraphAttributes(textPanel.getSelectionStart(),1,textPanel.getStyle(Hightlight背景),真);
    textPanel.setLogicalStyle(logicalStyle);


解决方案

更新:
我只是发现了一类名为Highlighter.I不认为你应该使用的setBackground风格。使用DefaultHighlighter类代替。

 荧光笔H = textPanel.getHighlighter();
h.addHighlight(1,10,新DefaultHighlighter.DefaultHighlightPainter(
Color.red));

在addHighlight方法的前两个参数是什么,但起始索引和要突出显示文本的结束索引。您可以调用此方法多timesto高亮显示文本的不连续线。

OLD答:

我不知道为什么setParagraphAttributes方法似乎犯规工作。但是,这样做似乎工作。

  doc.insertString(0,Hello World的,textPanel.getStyle(Hightlight背景));

也许你可以工作一个黑客解决这个现在...

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: 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));

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.

OLD ANSWER:

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天全站免登陆