As the title says, I'm wondering if there is a function to give me an x and y value for how much space the text will take so I can size my button accordingly. If not, could you please give me a code snippet that you may have to do the same job.
CodePudding user response:
You can use the FontMetrics class, for example:
public static int getTextWidth(Font font, String text) {
FontMetrics metrics = new FontMetrics(font) {
private static final long serialVersionUID = 345265L;
};
Rectangle2D bounds = metrics.getStringBounds(text, null);
return (int) bounds.getWidth();
}
public static int getTextHeight(Font font, String text) {
FontMetrics metrics = new FontMetrics(font) {
private static final long serialVersionUID = 345266L;
};
Rectangle2D bounds = metrics.getStringBounds(text, null);
return (int) bounds.getHeight();
}
To use these methods (perhaps in your use case):
int width = getTextWidth(jButton1.getFont(), "Hello There World");
int height = getTextHeight(jButton1.getFont(), "Hello There World");
Or...use the example shown in the provided link above.