【发布时间】:2015-03-23 15:50:03
【问题描述】:
在清除 textarea 中的文本后,我很难将光标设置回第一行的位置 0。
问题背景
我有一个textarea,它监听键事件。 textarea 只监听Enter 键,如果找到,要么提交文本,要么在文本区域中有“\n”时清除文本。
我尝试了以下所有方法,但都没有真正奏效。
- textArea.setText("")
- textArea.clear()
- textArea.getText().replace("\n", "")
- 从中移除焦点并重新放回去。
这是一个可运行并演示问题的测试项目。
主类:
public class Main extends Application {
Stage primaryStage;
AnchorPane pane;
public void start(Stage primaryStage){
this.primaryStage = primaryStage;
initMain();
}
public void initMain(){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("main.fxml"));
pane = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
launch();
}
}
控制器类:
public class Controller {
@FXML
TextArea textArea;
public void initialize() {
textArea.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
if (!textArea.getText().equals("")
&& !textArea.getText().contains("\n")) {
handleSubmit();
}
if (textArea.getText().contains("\n")) {
handleAsk();
}
}
}
});
}
/**
* After the user gives in a short input, that has no \n, the user submits by hitting enter.
* This method will be called, and the cursor jumps over to the beginning of the next line.
*/
public void handleSubmit(){
System.out.println("Submitted");
}
/**
* When this method is calls, the cursor is not in the first line.
* This method should move the cursor to the first position in the first line in the completely
* cleared text area.
*/
public void handleAsk(){
System.out.println("Asking and clearing text area.");
textArea.setText("");
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="317.0" prefWidth="371.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<children>
<TextArea fx:id="textArea" layoutX="78.0" layoutY="59.0" prefHeight="114.0" prefWidth="200.0" />
</children>
</AnchorPane>
我的问题是,光标不会跳回来...
【问题讨论】:
-
你的问题不是很清楚。您是否要从文本区域中删除所有文本?还是只是将光标移到开头?
-
删除所有内容(适用于 .setText(""))并将光标移回左上角(但光标仍停留在第二行,尽管将 Text 设置为空字符串) .
-
我无法重现。请创建并发布MCVE。
-
我可以在
Ubuntu 14.04 + Java 8u40上重现该问题。我已经编辑并添加了一个 MCVE,以帮助未来的观众。