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?