Java tutorial
//package com.java2s; /* * Copyright 2013 Simon Thiel * * This file is part of SitJar. * * SitJar is free software: you can redistribute it and/or modify * it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SitJar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with SitJar. If not, see <http://www.gnu.org/licenses/lgpl.txt>. * */ import java.awt.FontMetrics; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import javax.swing.JLabel; public class Main { public static int PADDING = 1; public static void setBoundsForJLabel(JLabel label, int xOffset, int yOffset) { setBoundsForComponent(label, label.getText(), xOffset, yOffset); } public static void setBoundsForComponent(JComponent comp, String text, int xOffset, int yOffset) { Rectangle bounds = calculateBoundsForComponent(comp, text, xOffset, yOffset); comp.setBounds(bounds); } public static Rectangle calculateBoundsForComponent(JComponent comp, String text, int xOffset, int yOffset) { FontMetrics fm = comp.getFontMetrics(comp.getFont()); Rectangle2D bounds = fm.getStringBounds(text, comp.getGraphics()); return new Rectangle(xOffset + (int) bounds.getX(), yOffset, (int) Math.ceil(bounds.getWidth()) + (PADDING * 2), (int) Math.ceil(bounds.getHeight() + fm.getDescent()) + (PADDING * 2)); } }