devpeterrrrr
devpeterrrrr

Reputation: 1

Java how to change color on g.drawString

I am trying to make the string currentTask in text red. However, it is white. I tried changing to red between like this, without any progress.

g.drawString("Task: " + g.setColor(Color.red) + currentTask, 13, 60);

g.setColor(Color.white);
g.drawString("Task: " + currentTask, 13, 60);

Upvotes: 0

Views: 105

Answers (1)

user16320675
user16320675

Reputation: 135

There are two drawString methods that accept an AttributedCharacterIterator. This is returned by AttributedString.getIterator(), so first such need to be created and configured.

Here a naïve solution:

var text = new AttributedString("Task: Test");
text.addAttribute(TextAttribute.FOREGROUND, Color.WHITE, 0, 6);
text.addAttribute(TextAttribute.FOREGROUND, Color.RED, 6, 10);

g.drawString(text.getIterator(), x, y);

obviously this must be expanded to concatenate currentTask instead of using the literal "Test" and have the respective indices calculated to be used in addAttribute


To do it without AttributedString, that is, setting the color of Graphics, you would have to do something like:

private static final LABEL = "Task: ";
...
g.setColor(Color.WHITE);
g.drawString(LABEL, x, y);
var delta = g.getFontMetrics().stringWidth(LABEL);
g.setColor(Color.RED);
g.drawString(currentTask, x+delta, y);

Upvotes: 2

Related Questions