如何在 JavaFX 中換行顯示標籤文字?
您可以使用 Label 元件在使用者介面上顯示文字元素/圖片。它是一種不可編輯的文字控制元件,主要用於說明應用程式中其他節點的用途。
在 JavaFX 中,您可以透過例項化 javafx.scene.control.Label 類來建立一個標籤。要建立一個標籤,您需要例項化此類。
一旦您建立了一個標籤,就可以使用 setMaxWidth() 和 setMaxHeight() 方法分別設定它的最大寬度和高度。
一旦您設定了標籤的最大寬度,其超出指定寬度的內容將被截斷。
為了避免這種情況,您可以換行顯示指定寬度內的文字,您需要呼叫 setWrapText() 方法。向此方法傳遞 true 作為引數時,超出指定寬度的標籤內容將換行到下一行。
示例
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; public class LabelWrapExample extends Application { public void start(Stage stage) { String text = "Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms."; //Creating a Label Label label = new Label(text); //wrapping the label label.setWrapText(true); //Setting the alignment to the label label.setTextAlignment(TextAlignment.JUSTIFY); //Setting the maximum width of the label label.setMaxWidth(200); //Setting the position of the label label.setTranslateX(25); label.setTranslateY(25); Group root = new Group(); root.getChildren().add(label); //Setting the stage Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Label Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
輸出
廣告