Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Feb 19, 1999

Timely Capture of Font Metrics

If you extend an AWT class to add text to a GUI component, then you probably need access to the font's metrics so that you can deduce the amount of space required by the text. But the component has no assigned font until its peer is created. This happens when the addNotify method is invoked, so you can call it in your class constructor, then get the font and its metrics. You will probably provide a setFont method to make adjustments when a different font is chosen, so consider using the following structure:
 
public void addNotify() {
    super.addNotify();
    setFont(getFont());
}

public void setFont(Font font) {
    super.setFont(font);
    FontMetrics metrics = getFontMetrics(font);
    ...
}
This simplifies your constructor by shifting all the font-related code into the setFont method where it belongs, and ensures that the addNotify method only gets called once when the class is instantiated.
Tom Yarker
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date