I think the above answer should be satisfactory, although not accurate. I'm not sure why, but the way it is. So, for example, I would focus any object / component on the panel. But with strings it is not so simple. This probably has something to do with the upward descent of the text, this is what I got from some code that I found on the network a long time ago.
The code is below. It shows a very simple example showing how it works in comparison with the above solution, you just need to comment / not comment on the corresponding code, run the program once for each option and compare / see.
I must admit that I am not the author of the algorithm (unfortunately, I do not remember his / her name - thanks for the code and good work), although I implemented methods that allow additional bias for x and y.
import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.HeadlessException; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public final class StringPainter { private StringPainter() { } public static void drawCenteredString(String s, int w, int h, Graphics g) { drawCenteredString(s, 0, 0, w, h, g); } public static void drawCenteredString(String s, int offsetX, int offsetY, int w, int h, Graphics g) { FontMetrics fm = g.getFontMetrics(); int x = (w - fm.stringWidth(s)) / 2 + offsetX; int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2) + offsetY; g.drawString(s, x, y); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createGUI(); } }); } private static void createGUI() throws HeadlessException { JPanel p = new JPanel() { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); String str = "TEST";
Hope this helps.
Enjoy Java, Boro.
source share