简体   繁体   中英

Why doesn't TextArea occupy entire area of ScrollPane in JavaFX? How to add scroll bars to TextArea in JavaFX?

In Swing I was to add JTextArea into JScrollPane in order JTextArea to have scroll bars. When I do the same in JavaFX , the behavior is different.

This example

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class SlideshowForSlipryPage2 extends Application {

    @Override
    public void start(Stage primaryStage) {


        primaryStage.setTitle("SlideshowForSlipryPage");
        primaryStage.setScene(
            new Scene(


                    new ScrollPane(
                        new TextArea() {{
                            setPromptText("[PROMPT 1]");
                        }}
                    )


                , 300, 250
            )
        );
        primaryStage.show();

    }

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

gives

在此处输入图片说明

ie text area is wider than a window and shorter than it.

Why and how to fix?

This issue has nothing to do with the pref width of the text area.

You must set the wrap property to true so that the text will wrap onto two lines when the cursor hits the edge of the container. 2 ways:

1) Using scene builder is the most simple way. Simple click "Wrap Text" in the properties of the TextArea.

2) Call the following method of the TextArea:

textArea.setWrapText(true);

Try this:

textArea.setPrefSize( Double.MAX_VALUE, Double.MAX_VALUE ); 

and set scrollpane size same as parent like this:

scrollPane.prefWidthProperty().bind(<parentControl>.prefWidthProperty());
scrollPane.prefHeightProperty().bind(<parentConrol>.prefHeightProperty());

I hope it resolves your query !!!

You have to call setFitToWidth(true) and setFitToHeight(true) on the ScrollPane, you can set those properties in the scene builder Layout tab after selecting the ScrollPane.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM