示例代码:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TestSpecialLibrary extends Application {
Text text;
TextField text4;
@Override
public void start(Stage stage) throws Exception {
Pane root=new Pane();
root.setPrefWidth(600);
root.setPrefHeight(300);
text=new Text("AqgWT");
text.setLayoutX(0);
text.setLayoutY(200);
TextField text1=new TextField("AqgWT");
text1.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if (newValue!=oldValue){
setDimensionFont(text1);
}
}
});
text1.setLayoutX(0);
text1.setLayoutY(0);
text1.setPrefWidth(200);
text1.setMinHeight(1);
text1.setMaxHeight(500);
text1.setPrefHeight(25);
TextField text3=new TextField();
text3.setLayoutX(300);
text3.setLayoutY(30);
text3.setPrefWidth(50);
text3.setMinHeight(1);
text3.setMaxHeight(500);
text3.setPrefHeight(25);
text4=new TextField();
text4.setLayoutX(300);
text4.setLayoutY(0);
text4.setPrefWidth(50);
text4.setMinHeight(1);
text4.setMaxHeight(500);
text4.setPrefHeight(25);
Button bs1=new Button("bs1");
bs1.setLayoutX(220);
bs1.setLayoutY(0);
bs1.setPrefWidth(50);
bs1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
text1.setPrefHeight(10+text1.getPrefHeight());
}
});
Button bs2=new Button("bs2");
bs2.setLayoutX(380);
bs2.setLayoutY(0);
bs2.setPrefWidth(50);
bs2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
text1.setFont(new Font(text1.getFont().getName(),
20));
text.setFont(new Font(text1.getFont().getName(),
20));
text4.setText(String.valueOf(text.getLayoutBounds().getHeight()));
}
});
root.getChildren().add(text1);
root.getChildren().add(bs1);
root.getChildren().add(text4);
root.getChildren().add(bs2);
root.getChildren().add(text);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
private void setDimensionFont(TextField txt){
Font font=txt.getFont();
font=new Font(font.getName(),20);
text.setFont(font);
double height = Math.round(text.getLayoutBounds().getHeight())
+ txt.getPadding().getTop() + txt.getPadding().getBottom();
double p3=Math.round(text.getLayoutBounds().getHeight());
if (height<=txt.getHeight()){
txt.setFont(font);
txt.positionCaret(txt.getCaretPosition());
text4.setText(String.valueOf(p3));
}
}
public static void main(String[] args) {
launch(args);
}
}
当我点击按钮bs1时,我更改了prefHeight
text1的TextField
,因此函数setDimensionFont启动,字体大小更改为20,而text4中显示的值为text.getLayoutBounds().getHeight()
是27岁。
然后我点击bs2,这个字体大小总是在20,但现在text.getLayoutBounds().getHeight()
的值是30 ......为什么?