Centralizar uma string relativa atraídos para o tamanho da janela?
Pergunta
Eu estou tentando centralizar uma string desenhado com "um" sistema", Font.BOLD, 90" fonte em Java. Eu tentei. (Largura / 2 - (Font.Size / 2 * num_of_chars)), mas que não funcionou
g2d.setFont(new Font("system", Font.BOLD, 90));
g2d.drawString("Pause", (int) ((800/2) - ((Font.getSize()/2) * 5)),270);
Solução
Use getFontMetrics()
. getStringBounds(String, Graphics)
obter os limites de a corda com a fonte atual.
Por isso, seria algo parecido com isto:
g2d.setFont(new Font("system", Font.BOLD, 90));
String msg = "Pause";
Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(msg, g2d);
g2d.drawString(msg, (int) ((getWidth() + bounds.getWidth()) / 2), 270);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow