11

How I can set the width of a TextField in JavaFX?

TextField userTextField = new TextField();

I tried this:

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

But I don't see any change.

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

3 Answers3

16

Works pretty fine:

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);
    }

}
Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
3

Just set this methods after you create the TextField:

TextField myTf = new TextField();
myTf.setPrefWidth(80);
myTf.setMaxWidth(80);
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
  • 2
    Please make sure to add an explanation to your answer. It helps future readers on understanding what you are suggesting. – Dessus May 02 '19 at 00:31
  • 1
    For anyone new wondering you can just do `TextField tf = new TextField(); tf.setMaxWidth(80);` without the need to set the prefered width – rodude123 Jun 19 '19 at 23:10
0

I had the same problem (that's how I landed on this page) and I fixed it by putting the textfield in a HBox. The problem might occur if the texfield is just put in a parent component alone where the siblings are layout managers. For example, putting it in a GridLayout alongside a VBox or HBox or a child GridLayout. Here is the code that did it;

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);

You can then add the HBox to the root or other parent layout manager.

Kenneth Murerwa
  • 778
  • 12
  • 16