gpt4 book ai didi

Javafx、TextArea 插入符在清除时不会移回第一行

转载 作者:行者123 更新时间:2023-12-02 11:35:58 24 4
gpt4 key购买 nike

在清除 textarea 中的文本后,我很难将光标设置回第一行的位置 0。

问题背景

我有一个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();
}
}

Controller 类:

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>

我的问题是,光标不会跳回来...

最佳答案

我找到了一个简短的解决方案:在调用所需的方法(handleAsk())后,该方法应该在完成后清除文本区域,我调用:keyEvent.consume();这会消耗 ENTER 的默认效果。

所以:首先,您显式定义的事件处理程序完成其工作,然后您可以决定是否希望将给定按键事件的默认效果作为“副作用”,如果没有,您可以使用它.

关于Javafx、TextArea 插入符在清除时不会移回第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29214583/

24 4 0