Timely Capture of Font Metrics

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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist