getting a null pointer when trying to create a new font

J

Justin

I have a class that extends a JDialog component. Within the
constructor, I call an addWidgets method. That method contains the
line in question:

Font nameFont = getFont().deriveFont(1,30);


This line is causing a null pointer exception. I dont understand why,
if someone could help me create the new font and explain to me why this
causes an error, it would be greatly appreciated.

Also the import list is as follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.font.*;


Thanks
 
T

Thomas Weidenfeller

Justin said:
I have a class that extends a JDialog component. Within the
constructor, I call an addWidgets method. That method contains the
line in question:

Font nameFont = getFont().deriveFont(1,30);


This line is causing a null pointer exception. I dont understand why,

A component which hasn't been realized does this. It's the way AWT and
Swing work.

/Thomas
 
J

Justin

Ok, but did I not initialize it on the line:

Font nameFont = getFont().deriveFont(1,30);


???
 
J

Joe Attardi

component has been shown.

Justin,
This is why code like that can be troublesome. If getFont() returns
null, as it is in this case, in your code there's no way to stop the
call to deriveFont(1, 30) and thus your NullPointerException.

While more verbose, something like this is a little more
error-friendly:

Font nameFont = getFont();
if (nameFont != null)
nameFont = nameFont.deriveFont(1, 30);

The burden is on you to then provide graceful handling of this error
condition, but at least your user won't see a NullPointerException...
 
T

Tor Iver Wilhelmsen

Justin said:
Ok, but did I not initialize it on the line:

Font nameFont = getFont().deriveFont(1,30);

getFont() requires a native peer, and that won't exist until the
component has been shown.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top