This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with TEXT  RSS feed

 
danesh far
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getGraphics() only returns a Graphics object once the component has physically
appeared on the screen. Before then (such as during the constructor), getGraphics() may return null, and so you'll get NullPointerExceptions like you see here.

You can (and should) do this work when you override the paintComponent() method; the Graphics argument won't be null.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Swing / AWT / SWT / JFace forum...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!