它认为已经定义了解决方案。我想这么想,但不幸的是结果是一样的尝试,第三个解决方案没有改变文本颜色...... ..
我试图将JTextPane中某个单词的颜色更改为红色 显示它的状态。有很多例子,我尝试了几个,但最终的结果是文本保持不变或整个文本的颜色发生变化。
我会在这里放一段代码,因为这个类很大
..
textPane = new JTextPane();
textPane.setFont(new Font("Arial", Font.PLAIN, 12));
..
String productName = "PC";
String vendorName = "DELL";
String statusOfProd = "OFF";
String theObject = "Product " + productName + " Vendor " + vendorName;
String taData = theObject + "\n";
textPane.setText(taData);
if (statusOfProd.equals("OFF")){
addColor2Pane(productName, Color.RED);
}
..
private void addColor2Pane(String value2Change, Color color2Use) {
String theData = textPane.getText();
int v2cIndex = theData.indexOf(value2Change);
int v2cLen = value2Change.length();
try {
textPane.getHighlighter().addHighlight(v2cIndex, v2cIndex + v2cLen,
new DefaultHighlighter.DefaultHighlightPainter(color2Use));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
..
// Attributes
protected JTextPane textPane;
public static String taData;
上述方法的结果无效。如果我更改" addColor2Pane" 结果下面的方法会渲染窗格RED中的所有文本,这不是我想要实现的。
..
private void addColor2Pane(String value2Change, Color color2Use) {
StyleContext sc = StyleContext.getDefaultSytleContext();
AttributeSet aSet = sc.addAttribute(sc.getEmptySet(),
StyleConstants.Foreground,
color2Use);
aSet = sc.addAttribute(aSet,
StyleConstants.FontFamily,
"Lucida Console");
aSet = sc.addAttribute(aSet,
StyleConstants.Alignment,
StyleConstants.ALIGN_LEFT);
int v2cInd = theData.indexOf(value2Change);
int v2cLen = value2Change.length();
textPane.setCaretPosition(v2cInd);
textPane.setCharacterAttributes(aSet, true);
textPane.replaceSection(value2Change);
}
所需的结果只是将productName的颜色设置为RED。建议?