Sunday, April 16, 2006

Two java tricks

I found two useful java tricks today.
  • Calculate the width of a string in pixels
Just use the following code:
Font currentFont = biggestFont;
Font currentFont = new Font(/* define your own font */);
FontMetrics currentMetrics = getFontMetrics(currentFont); // 1
String longString = "This is not a long string!";
Although getFontMetrics from Toolkit is deprecated, JComponent.getFontmetrics is not. More can be found in the java forums.


  • Recurring tasks to update the GUI
The Timer object allows you to schedule TimerTasks at a specified date or at regular intervals. It is very useful when you are polling data which will be later painted on your GUI components.

No comments: