As soon as the background component i.e. everything behind your menu has been visualized; it has a Graphics object that you can use to get metrics for a given font just once.
You certainly do not want to do this in the paint method, which should be as light as possible. I would hang this code on a listener that gets called when the component is first displayed. It can store the resulting FontMetrics object somewhere where you can access it later, or in the paint method to draw these menu boxes.
Instead of defining measurements of menu graphics at the last moment, i.e. When paint ing, it might be a good idea to create some components to represent your menu. You can place these components on the glass panel for more information here , so that they pop up above everything else, and you will have the added bonus that these components can take mouse clicks and trigger listening events on them, and since they only capture events on their own geometry , you donโt even need to determine which part of the menu was clicked, if at all possible.
Another advantage of using components here is that you can completely circumvent the requirement for messing around with font labels. There are ready-made menu items, or you can just use JLabels , and you can specify their alignment, you can use LayoutManager to size the boxes along the width of the largest label, etc.
source share