是否可以在Java Swing中更改段落的背景颜色?我试图使用setParagraphAttributes方法(下面的代码)来设置它,但似乎不起作用。更改JTextPane中段落的背景颜色(Java Swing)
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);
请注意,使用特定背景颜色设置段落元素属性(正确)将仅影响该段落的字符。它不会影响该段落右侧(或左侧)的空间。然而,可以为JTextComponent的Highlighter提供一个自定义的'Highlighter.HighlightPainter'来做到这一点。 –