0

It's thought that the solution has been defined already. I'd like to think so but unfortunately the results are the same trying yet a 3rd solution produced no change to the text color... ..

I'm trying to change the color of a certain word in a JTextPane (to red) to show it's status. There are a number of examples and I've tried several but the end result is either the text remains unchanged or the entire text's color changes.

I will place a snippet of code here because the class is rather large

..
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;

The result of the above method has no effect. If I change the "addColor2Pane" method to below the result renders all text in the pane RED which is not what I'm trying to achieve.

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

}

The desired result is ONLY have the color of the productName set to RED. Suggestions?

Fred
  • 49
  • 7
  • Possible duplicate of [How to add text different color on JTextPane](https://stackoverflow.com/questions/6068398/how-to-add-text-different-color-on-jtextpane) – Frakcool Jun 15 '17 at 18:46
  • *"I will place a snippet of code here because the class is rather large"*, We don't need your whole code or code snippets, but a valid [mcve] that demonstrates your issue and your best approach into solving it yourself C: – Frakcool Jun 15 '17 at 18:47

0 Answers0