java - Draw Text in Middle of the Screen -


i'm trying draw text in middle of jframe window, , it's off little bit.

here's i've tried :

fontmetrics fontmetrics = g.getfontmetrics(font);  // draw title g.setcolor(color.white); g.setfont(font); int titlelen = fontmetrics.stringwidth("level 1 over!"); g.drawstring("level 1 over!", (screenwidth / 2) - (titlelen / 2), 80); 

i've found textlayout class gives better dimensions string fontmetrics.

@override public void paintcomponent(graphics g) {     super.paintcomponent(g);      if (font == null) {         return;     }      graphics2d g2d = (graphics2d) g;     fontrendercontext frc = g2d.getfontrendercontext();     textlayout layout = new textlayout(samplestring, font, frc);     rectangle2d bounds = layout.getbounds();      int width = (int) math.round(bounds.getwidth());     int height = (int) math.round(bounds.getheight());     int x = (getwidth() - width) / 2;     int y = height + (getheight() - height) / 2;      layout.draw(g2d, (float) x, (float) y); } 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -