JavaFX:如何将 TextArea 的操作限制在最后一行?
JavaFX: How to restrict manipulation of TextArea to last row?
我正在尝试使用 JavaFX 模拟 shell。我想在同一个 TextArea 中处理输出和输入,所以我希望能够编辑和写入 only 提示所在的 TextArea 的最后一行,就像shell.
关于如何做到这一点有什么想法吗?
您可以子类化 TextArea
并防止在编辑发生的点之后有换行符时对文本进行更改。根据 Richard Bair's blog post,您需要覆盖的唯一方法是 replaceText()
和 replaceSelection
。
这是一个简单的例子:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ConsoleTest extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setScene(new Scene(new BorderPane(new Console()), 600, 600));
primaryStage.show();
}
public static class Console extends TextArea {
@Override
public void replaceText(int start, int end, String text) {
String current = getText();
// only insert if no new lines after insert position:
if (! current.substring(start).contains("\n")) {
super.replaceText(start, end, text);
}
}
@Override
public void replaceSelection(String text) {
String current = getText();
int selectionStart = getSelection().getStart();
if (! current.substring(selectionStart).contains("\n")) {
super.replaceSelection(text);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
如果你想显示一个提示(当然是不可编辑的),那么逻辑有点棘手,但应该相当简单。对于传递给这些方法的 text
参数包含换行符的情况,您可能还需要一些特殊处理。
我正在尝试使用 JavaFX 模拟 shell。我想在同一个 TextArea 中处理输出和输入,所以我希望能够编辑和写入 only 提示所在的 TextArea 的最后一行,就像shell.
关于如何做到这一点有什么想法吗?
您可以子类化 TextArea
并防止在编辑发生的点之后有换行符时对文本进行更改。根据 Richard Bair's blog post,您需要覆盖的唯一方法是 replaceText()
和 replaceSelection
。
这是一个简单的例子:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ConsoleTest extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setScene(new Scene(new BorderPane(new Console()), 600, 600));
primaryStage.show();
}
public static class Console extends TextArea {
@Override
public void replaceText(int start, int end, String text) {
String current = getText();
// only insert if no new lines after insert position:
if (! current.substring(start).contains("\n")) {
super.replaceText(start, end, text);
}
}
@Override
public void replaceSelection(String text) {
String current = getText();
int selectionStart = getSelection().getStart();
if (! current.substring(selectionStart).contains("\n")) {
super.replaceSelection(text);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
如果你想显示一个提示(当然是不可编辑的),那么逻辑有点棘手,但应该相当简单。对于传递给这些方法的 text
参数包含换行符的情况,您可能还需要一些特殊处理。