JavaFX TextArea
时间:2020-01-09 10:36:42 来源:igfitidea点击:
JavaFX TextArea控件使JavaFX应用程序的用户能够输入跨多行的文本,然后可由应用程序读取。 JavaFX TextArea控件由类javafx.scene.control.TextArea表示。
创建一个TextArea
我们可以通过创建TextArea类的实例来创建TextArea控件。这是一个JavaFXTextArea实例化示例:
TextArea textArea = new TextArea();
将TextArea添加到场景图
为了使JavaFX" TextArea"可见,必须将" TextArea"对象添加到场景图。这意味着将其添加到"场景"对象,或者作为添加到"场景"对象的布局的子级。
这是一个将JavaFXTextArea添加到场景图的示例:
package com.Hyman.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
VBox vbox = new VBox(textArea);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
运行上面的JavaFXTextArea示例的结果是一个看起来像这样的应用程序:
读取TextArea的文本
我们可以通过getText()方法读取输入到TextArea中的文本。这是一个通过其getText()方法读取JavaFX TextArea控件的文本的示例:
String text = textArea.getText();
这是一个完整的示例,显示一个TextArea和一个Button,当单击该按钮时,该文本读取输入到TextArea中的文本:
package com.Hyman.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
Button button = new Button("Click to get text");
button.setMinWidth(50);
button.setOnAction(action -> {
System.out.println(textArea.getText());
textArea.setText("Clicked!");
});
VBox vbox = new VBox(textArea, button);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
设置TextArea的文本
我们可以通过控件的setText()方法来设置TextArea控件的文本。这是一个通过setText()设置TextArea控件的文本的例子:
textArea.setText("New Text");

