I am writing an application to show a text and measure different aspect of it as follows:
// Simple animation with Java
import java.awt.*;
import javax.swing.*;
public class AnimateEx extends JFrame {
String theString = "Boing!!!";
private int stringTop, stringBottom, stringWidth;
public void paint(Graphics g)
{
g.drawString(theString, 100,200);
}
public AnimateEx()
{
setSize(770,420);
setFont( new Font("TimesRoman", Font.BOLD+Font.ITALIC, 24));
setBackground(Color.yellow);
setForeground(Color.red);
Graphics g=this.getGraphics();
FontMetrics fm= g.getFontMetrics();
stringWidth = fm.stringWidth(theString);
stringTop = fm.getAscent();
stringBottom = fm.getDescent();
}
public static void main(String[] args){
AnimateEx ex= new AnimateEx();
ex.setVisible(true);
}
}
When I run the application without the followin lines in the constructor :
FontMetrics fm= g.getFontMetrics();
stringWidth = fm.stringWidth(theString);
stringTop = fm.getAscent();
stringBottom = fm.getDescent();
(which I add to get some text measure )it works well but after adding those lines I got this error (no error during compile but have it when run):
Exception in thread "main" java.lang.NullPointerException
at AnimateEx.<init>(AnimateEx.java:20)
at AnimateEx.main(AnimateEx.java:28)
