我正在尝试使用 JavaFXML 创建一个 GUI,并且我在其中使用了一个 TextArea。将文本添加到 TextArea 时,默认将文本放在顶部,我希望文本从底部开始,并在追加时添加到前一个文本的下方。如果有帮助,我正在尝试模拟终端。
目前我正在使用 css 来设置 UI 的样式并更改颜色,效果很好,但我无法让文本服从。如果有一种方法可以将 css 属性添加到 TextArea,以便文本与底部对齐,那就太好了。
这就是我的所有代码在功能上所做的,将我在 TextField 中键入的任何内容都提取出来并将其附加到上面的文本区域,该文本区域被禁用以防止用户输入。
textarea.appendText("\n" + textfield.getText());
PS 我的代码请求集中在文本字段上,如下所示:
@Override
public void initialize(URL url, ResourceBundle rb) {
Platform.runLater(new Runnable() {
@Override
public void run() {
textfield.requestFocus();
}
});
}
但是如果用户点击它,我如何将焦点设置回文本字段?我希望在选择我的应用程序时键入时始终将文本输入文本字段,但如果单击文本字段,焦点将被移除并且不会在任何地方输入击键。
最佳答案
我认为 TextArea
没有这个功能。您可以做的是用所需的行为实现您自己的类。下面是它的外观示例:
import java.util.ArrayList;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
public class MCVE extends Application {
@Override
public void start(Stage primaryStage) {
try {
BtmAlignedTextArea area = new BtmAlignedTextArea();
TextArea msgArea = new TextArea();
msgArea.setPrefHeight(100);
Button sendButton = new Button("Send");
sendButton.setMinWidth(Region.USE_PREF_SIZE);
sendButton.prefHeightProperty().bind(msgArea.heightProperty());
HBox msgBox = new HBox(msgArea, sendButton);
msgBox.setAlignment(Pos.CENTER_LEFT);
msgArea.prefWidthProperty().bind(msgBox.widthProperty().subtract(sendButton.widthProperty()));
msgArea.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode().equals(KeyCode.ENTER)) {
sendButton.fire();
}
});
sendButton.setOnAction(e -> {
area.addRow(msgArea.getText());
msgArea.clear();
// This is just a fix because the caret positions itself on the
// second row after msgArea has been cleared for some reason.
Platform.runLater(() -> msgArea.positionCaret(0));
});
VBox root = new VBox(area, msgBox);
area.prefHeightProperty().bind(root.heightProperty().subtract(msgArea.heightProperty()));
area.prefWidthProperty().bind(root.widthProperty());
msgBox.prefWidthProperty().bind(root.widthProperty());
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
class BtmAlignedTextArea extends VBox {
private ArrayList<Label> rows = new ArrayList<Label>();
public BtmAlignedTextArea() {
this.setAlignment(Pos.BOTTOM_LEFT);
this.setPadding(new Insets(10));
}
public void addRow(String text) {
Label label = new Label(text);
this.getChildren().add(label);
rows.add(label);
}
public ArrayList<Label> getRows() {
return rows;
}
}
}
关于java - 将文本区域的文本设置为与底部对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882455/