HOWTO · JavaFX

JavaFX TextArea 換行文字

本教程演示瞭如何使用 JavaFX 在 TextArea 中換行。

本頁內容

文字區域用於輸入大文字。本教程演示瞭如何使用 JavaFX 在 TextArea 中換行。

JavaFX TextArea 換行文字

文字區域用於獲取大文字作為輸入。有時我們需要編輯一些大文字,不想再寫整個文字;為此,我們可以將文字區域中的先前文字換行並編輯該部分。

setWrapText(true) 方法將文字包裝在 TextArea 或任何其他元素中。按照分步過程將文字換行在文字區域中。

  • 建立一個擴充套件 Application 的類。
  • 用內容建立一個 TextArea
  • 將文字區域的方法 setWrapText() 設定為 true
  • 設定 TextArea 的大小。
  • 建立場景並將其顯示在舞臺上。
  • 最終輸出將是包裹在 TextArea 中的文字。

讓我們嘗試根據上述步驟實現一個示例。

package delftstack;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class TextArea_Wrap extends Application {
  public void start(Stage TextArea_Stage) {
    String Content = "DelftStack is a resource for everyone interested in programming, "
        + "embedded software, and electronics. It covers the programming languages "
        + "like Python, C/C++, C#, and so on in this website's first development stage. "
        + "Open-source hardware also falls in the website's scope, like Arduino, "
        + "Raspberry Pi, and BeagleBone. DelftStack aims to provide tutorials, "
        + "how-to's, and cheat sheets to different levels of developers and hobbyists..";
    // Create a Label
    TextArea Text_Area = new TextArea(Content);
    // wrap the textArea
    Text_Area.setWrapText(true);
    // Set the maximum width of the textArea
    Text_Area.setMaxWidth(300);
    // Set the position of the textArea
    Text_Area.setTranslateX(30);
    Text_Area.setTranslateY(30);
    Group TextArea_Root = new Group();
    TextArea_Root.getChildren().add(Text_Area);
    // Set the stage
    Scene TextArea_Scene = new Scene(TextArea_Root, 595, 150, Color.BEIGE);
    TextArea_Stage.setTitle("Label Example");
    TextArea_Stage.setScene(TextArea_Scene);
    TextArea_Stage.show();
  }
  public static void main(String args[]) {
    launch(args);
  }
}

上面的程式碼將建立一個文字區域,其中包含文字。見輸出:

TextArea 換行文字