正如標題所說,我想知道是否有一個函式可以給我一個x和y值,以確定文本將占用多少空間,這樣我就可以相應地確定我的按鈕的大小。如果沒有,你能不能給我一個你可能有的代碼片段,以完成同樣的作業。
uj5u.com熱心網友回復:
你可以使用FontMetrics類,例如:
public static int getTextWidth(Font font。字串文本) {
FontMetrics metrics = new FontMetrics(字體) {
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(字體) {
private static final long serialVersionUID = 345266L;
};
Rectangle2D bounds = metrics.getStringBounds(text, null)。
return (int) bounds.getHeight()。
}
要使用這些方法(也許在你的用例中):
int width = getTextWidth(jButton1. getFont(), "Hello There World")。)
int height = getTextHeight(jButton1.getFont(), "Hello There World") 。
或者...使用上面提供的鏈接中顯示的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/310269.html
標籤:
