How can I make a JLabel whose size is just big enough for the text, with no borders?

Scott Stanchfield

JLabel actually does provide just enough space for the text plus the leading (space between lines).

You can do something like the following, though it is not recommended. This subclass of JLabel only provides enough room for the ascent and descent of a font. Note that there may still appear to be some space, as some characters in the font may require additional space above or below a letter like "M" or "y".

import javax.swing.*;
import java.awt.*;

public class TightJLabel extends JLabel {
  public Dimension getPreferredSize() {
    FontMetrics fm = getFontMetrics(getFont());
    return new Dimension(fm.stringWidth(getText()),
                         fm.getAscent()+fm.getDescent());
  }
}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact