Search code examples
javaswingjlabelfontmetrics

JLabel width always returning 0 in the constructor. Then if the width is over X value, insert a line break?


I've created a class which extends the JLabel class. This class essentially makes it "nicer" for me to attach the relevant IconImage to my JLabel, and size it correctly too.

When I create a new JLabel, by code, I now do it by something = new MyClass("message", 1); For that code above I'd have the MyClass(String msg, int type) {} constructor in place. In this constructor I want to be able to get the width of the text the user specifies. If that width is over a certain value, let's say 300px then I'd like to insert a line break (essentially making the JLabel word-wrap according to a maximum width).

I've removed the part in the code below which adds the image to the JLabel because that's not relevant to the question - I've created a separate class to handle this, which already works.

package org.me.myimageapp;

import javax.swing.JLabel;

/**
 *
 * @author Jordan
 */
public class chatBubble extends JLabel {

public static final int BUBBLE_TO_USER = 1;
public static final int BUBBLE_FROM_USER = 2;

chatBubble(String message, int bubble_type) {
    if ( (bubble_type!=1) && (bubble_type!=2) ) {
        return;
    }

    this.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    this.setText(message);
    this.setVisible(true);
    System.out.println("WIDTH: "+this.getSize().toString()); //WIDTH: java.awt.Dimension[width=0,height=0]

}

}

When I run this code it returns "WIDTH: java.awt.Dimension[width=0,height=0]" like I placed in the comments.

Is there any way that I can get the width of a JLabel in the constructor? Also is there any way that exists for a JLabel which would allow me to word wrap?


Solution

  • Any Swing component's size will be zero until it has been rendered, no way around that. You could estimate the size of the text though by using the FontMetrics class (check out the link to the API).

    There are also kludges available to gain you word wrap in a JLabel by using HTML

    Edit 1
    Regarding your question:

    What would you suggest being the best way to estimate it? Something like counting the characters and the multiplying by an average character width?

    I don't know as I haven't used FontMetrics. I'd recommend playing with it some and seeing what you can come up with, and also searching for its use in answers on this forum.

    Regarding my second solution, please check my answer to a question here: word-wrap-in-jlist-items