Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;

import javax.swing.JLabel;

public class Main {
    private static JLabel defaultLabel = new JLabel();

    public static Dimension getTextDimension(final String text, final Font font) {
        if (defaultLabel == null) {
            defaultLabel = new JLabel();
        }

        // get metrics from the graphics
        FontMetrics fontMetrics = defaultLabel.getFontMetrics(font);

        // get the height of a line of text in this
        // font and render context
        int hgt = fontMetrics.getHeight();
        // get the advance of my text in this font
        // and render context
        int adv = fontMetrics.stringWidth(text);
        // calculate the size of a box to hold the text
        Dimension size = new Dimension(adv, hgt);

        return size;
    }
}