Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Font metrics extra space with JLabel

843807Dec 12 2009 — edited Dec 13 2009
Hello all,

I'm new at Java and have been trying to solve this problem hopefully you guys can help. When creating a JLabel using a specific font and setting the JLabels size by the fonts width and the fonts height I can get the exact measure of a characters width using FontMetrics but I can't seem to find anyway to get the exact height of a character. I can get ascent and descent etc. but my goal is to somehow either find a way to crop all the empty space that a specific character doesn't take up or find the amount of space above and below the character. I'm thinking the second goal will be most likely. In the example below if you run the code you will see a opaque JLabel with a background color of red and the letter "y" in black. What I want to do is crop or somehow measure the extra space above and below the letter. Any help would be great and I hope you understand my problem I'm not to good at explaining things. Thanks again.
import java.awt.*;
import javax.swing.*;


public class Main extends JFrame{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }


    public Main() {
        this.setTitle("Letter extra space example");
        this.setSize(150,100);
        this.setLocationRelativeTo(null);
        this.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Font for JLabel to use
        Font font = new Font("Arial",Font.PLAIN,50);
        FontMetrics metrics = this.getFontMetrics(font);

        //create JLabel
        JLabel label = new JLabel("y");
        label.setFont(font);
        label.setBounds(5,5,metrics.charWidth('y'),metrics.getHeight());
        label.setOpaque(true);
        label.setBackground(Color.red);
        label.setForeground(Color.black);

        this.add(label);
        this.setVisible(true);
    }

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 10 2010
Added on Dec 12 2009
11 comments
768 views