Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to calculate the length of a string in pixels

843807Aug 8 2005 — edited Jan 20 2006
I am relatively new to Java GUI building, so this is a pretty simple question.

I have written a very simple program which takes string input from the user and when the user presses a button, the program prints out the string in a random location and random color.

I am trying to calculate the length of a string in pixels using the J++ 6.0 development environment (yes, I know....heresy, but my professor requires us to use it). This is because the string should fit completely on the graphics context, not running over its boundaries. Here is a copy of the relevent code from the button's event handler:

private void btnRand_click(Object source, Event e)
{
/*Use a graphics object to draw the string
entered by the user in a random
location (x,y) in the form*/
Graphics drawTxt = this.createGraphics();
drawTxt.setFont(new Font("Arial", 14.0f));

//Get String value entered by user
String str = edString.getText();

int width = metrics.stringWidth(str); /*Variables for coordinates (x,y), and
colors ( r)ed, g)reen, b)lue))*/
int x = 0, y = 0, r, g, b;
x = Math.abs(nextValue.nextInt() % this.getWidth());
y = Math.abs(nextValue.nextInt() % (this.getHeight()) -
(2*(lblTitle.getHeight())));

//Choose random color set
r = Math.abs(nextValue.nextInt() % 256);
g = Math.abs(nextValue.nextInt() % 256);
b = Math.abs(nextValue.nextInt() % 256);

//Set text color
drawTxt.setTextColor(new Color(r, g, b));

//Draw the string in a random location
drawTxt.drawString(str, x, y);
}

'metrics' is a variable of type FontMetrics, which I have declared already at the beginning of the class. The line in bold is causing a nullPointerException whenever the event handler is executed. Why?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 17 2006
Added on Aug 8 2005
5 comments
442 views