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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: