setBackground() method is not working for Graphics2D object
You never filled the image or drew any filled shape. Setting the background color doesn't change the image, it only selects the color that will be used for the next operation that fills with the background color. It's like putting paint on your paintbrush, but never painting on the canvas. But as the docs for clearRect say, you should use setColor followed by fillRect instead.
There also seems to be a problem with the way you calculate the position to draw the string on the screen. You use stringWidth - width/2
. The width is 128. Let's say the stringWidth is 32. Then that will be 32 - 128/2, or 32 - 64, or -32. Depending on the width of the string, at least part of it will be drawn outside the buffered image. It will be clipped, and either invisible, or only partly visible.
I would suggest width/2 - stringWidth/2
(or just (width - stringWidth)/2
). The idea is to start at width/2, the center of the image, and back up half the width of the string, so that it is centered on the image. Although, I do not know how you intend for the results to look.