Graphics g = getGraphics(); Font font = new Font("Serif", Font.PLAIN, 12); FontMetrics metrics = g.getFontMetrics(font); int width = metrics.stringWidth("Hello, world!"); int height = metrics.getHeight();In this example, we create a `Graphics` object and a `Font` object. We then use the `getFontMetrics` method to get the metrics for the font in the `Graphics` context. We then calculate the width and height of the string "Hello, world!" using the `FontMetrics` object. This method is part of the `java.awt` package library.