Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
May 29, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Tame Truncated Text

You may notice that the first or last character in a Label's text can get partially chopped off by some implementations of the Java Virtual Machine. Older versions of browsers seem particularly poor in this respect. Oddly, the left side of a right justified Label is often the victim. I suspect the weakness is in the accuracy of the FontMetrics which are supposed to provide the width of each character, but this doesn't help when you just want to get a good looking applet or application developed. In the following class, each Label's text is padded with spaces to avoid truncation.
import java.awt.*;
public class PaddedLabel extends Label {
// Constructor, left justification
    public PaddedLabel(String text) {
        this(text, LEFT);
// Constructor, specified justification
    public PaddedLabel(String text, int justification) {
        super(" " + text.trim() + " ", justification);
// Accessor, returns text without padding
    public String getText() {
        return super.getText().trim();
// Accessor, sets text with padding
    public void setText(String text) {
        super.setText(" " + text.trim() + " ");
Tom Yarker
Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date