string - How to center a drawString in Java? -


how can center text of drawstring in java? want it can centered along screen dynamically, whether change height , width of box or not. found this codebut don't know how use it. can explain?

horizontally...

string text = "..."; graphics2d g2d = (graphics2d)g.create(); fontmetrics fm = g2d.getfontmetrics(); int x = (getwidth() - fm.stringwidth(text)) / 2; 

vertically...

string text = "..."; graphics2d g2d = (graphics2d)g.create(); fontmetrics fm = g2d.getfontmetrics(); int y = ((getheight() - fm.getheight()) / 2) + fm.getascent(); 

also demonstrated here

also have @ 2d graphics , working text apis


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -