get String Size on Component - Java Swing

Java examples for Swing:JComponent

Description

get String Size on Component

Demo Code


//package com.java2s;

import java.awt.Dimension;

import java.awt.FontMetrics;

import javax.swing.JComponent;

public class Main {
    public static Dimension getStringSize(JComponent c, String text) {
        FontMetrics metrics = c.getFontMetrics(c.getFont());
        int hgt = metrics.getHeight();
        int adv = metrics.stringWidth(text);
        return new Dimension(adv + 2, hgt + 2);
    }//w  w  w .ja  v a  2  s  . co m
}

Related Tutorials