Java tutorial
//package com.java2s; import java.awt.Graphics; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class Main { public static void setLabelTop(JLabel label, String str, int width, int height) { Graphics g = label.getGraphics(); label.setText(str); int strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), str); int lX = width / 2 - strWidth / 2; int lY = g.getFont().getSize() / 2; //System.out.printf("\"label\"+%s X:%d,Y:%d\n",str,lX,lY); label.setBounds(lX, lY, strWidth, g.getFont().getSize()); } }