Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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() {

public void setFont(Font 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.



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