在JavaFX中设置TextField宽度

问题描述 投票:8回答:3

如何在JavaFX中设置TextField的宽度?

TextField userTextField = new TextField();

我试过这个:

TextField userTextField = new TextField();
userTextField.setPrefWidth(80);

但我没有看到任何变化。

javafx-2 javafx javafx-8
3个回答
15
投票

工作得很好:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class TextFieldWidthApp extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField userTextField = new TextField();
        userTextField.setPrefWidth(800);
        primaryStage.setScene(new Scene(userTextField));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

1
投票
    TextField.setPrefWidth(80);
    TextField.setMaxWidth(80);

0
投票

我有同样的问题(这就是我登陆这个页面的方式)并且我通过将文本字段放在HBox中来修复它。如果texfield只是放在父组件中,兄弟姐妹是布局管理器,则可能会出现问题。例如,将它与VBox或HBox或子GridLayout一起放在GridLayout中。这是执行它的代码;

HBox hbForTextField = new HBox();
TextField sample = new TextField();
sample.setAlignment(Pos.CENTER);//Align text to center
sample.setPrefWidth(120);//Set width

//Add the texfield to the HBox
hbForTextField.getChildren().addAll(generatedPassword);

然后,您可以将HBox添加到根或其他父布局管理器。

© www.soinside.com 2019 - 2024. All rights reserved.