这是我编写的一个简单程序,在舞台上的圆角矩形背景上有一个按钮。
package definitive_guide;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.SceneBuilder;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPaneBuilder;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class SingleButton extends Application {
Button btn;
Scene scene;
StackPane stack;
Rectangle roundedRectangle;
@Override
public void start(Stage stage) throws Exception {
btn = ButtonBuilder
.create()
.font(Font.font("DejaVu Sans Mono",22))
.text("Hello World")
.build();
roundedRectangle = RectangleBuilder
.create()
.width(300)
.height(300)
.arcHeight(150)
.arcWidth(200)
.fill(Color.rgb(128, 128, 128))
.build();
stack = StackPaneBuilder
.create()
.children(roundedRectangle , btn)
.build();
stack.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
scene = SceneBuilder
.create()
.root(stack)
.build();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Application.launch("definitive_guide.SingleButton.java");
}
}
目前,矩形的长度、宽度和弧度值是手动输入的。因此,它们不是动态的。
我希望能够根据文本的大小加上一些填充来设置其大小,以便在不同分辨率的设备上具有一致的外观和感觉。
在 Swing 中,FontMetrics
很方便,但我不知道在 JavaFX 中该怎么做。
我该怎么做?
最佳答案
如果您真的关心文本
,请尝试以下操作:
final Text text = new Text("Click me");
text.setFont(Font.font("DejaVu Sans Mono", 42));
text.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// set with long text
text.setText("Hello Sun, Hello Galaxy, Hello Space!");
}
});
text.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
if(oldValue.getHeight() != newValue.getHeight() || oldValue.getWidth()!= newValue.getWidth()) {
roundedRectangle.setWidth(newValue.getWidth() + 100);
roundedRectangle.setHeight(newValue.getHeight() + 30);
}
}
});
如果您对按钮的文本感兴趣,您可以尝试直接绑定(bind)到按钮:
roundedRectangle.widthProperty().bind(btn.widthProperty().add(100));
roundedRectangle.heightProperty().bind(btn.heightProperty().add(30));
弧宽和高度值也是可绑定(bind)的:
roundedRectangle.arcHeightProperty()
roundedRectangle.arcWidthProperty()
关于java - 在 JavaFX 中测量文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361211/