I'm having trouble centering my text on an applet window. For whatever reason, I believe it's reporting the width incorrectly, whether I use stringWidth() or assign a bounding box to a 2d rectangle. If you run the code, you'll see what I'm talking about. Any help is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Shapes extends JApplet implements Runnable
{
private Dimension wh;
Thread firstThread;
String sS;
FontMetrics fm;
int textWidth;
int textHeight;
int sleep;
Rectangle2D rect;
private Image backImage;
private Graphics backGraphics;
public void init()
{
wh = getSize();
sleep = 50;
sS = "SIM STUDIO";
}
public void paint(Graphics g)
{
if(backGraphics == null)
{
backImage = createImage(wh.width, wh.height);
backGraphics = backImage.getGraphics();
}
fm = g.getFontMetrics();
rect = fm.getStringBounds(sS, g);
backGraphics.setFont(new Font("SansSerif", Font.BOLD, 26));
textWidth = (wh.width - ((int) (rect.getWidth())))/2;
textHeight = (wh.height + fm.getAscent())/2;
backGraphics.setColor(Color.blue);
backGraphics.fillRect(0, 0, wh.width, wh.height);
backGraphics.setColor(Color.white);
backGraphics.drawString(sS, textWidth + 2, textHeight + 2);
backGraphics.setColor(Color.lightGray);
backGraphics.drawString(sS, textWidth, textHeight);
showStatus("font width is " + fm.stringWidth(sS) + "and" + ((int)
(rect.getWidth())) + " total width " + wh.width);
backGraphics.fillRect(300, 100, 5, 5);
g.drawImage(backImage, 0, 0, this);
}
public void destroy()
{
}
}