我在我的JavaFX主类中编写了以下代码:
package jfxTest;
import java.util.Random;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
private static int selectionIndex = 0;
private static TextArea textArea;
@Override
public void start(Stage primaryStage) {
System.out.println("Starting JavaFX Window...");
StackPane rootPane = new StackPane();
textArea = new TextArea();
textArea.setText("TEST");
textArea.setEditable(false);
createRandomOptions(8);
textArea.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode().equals(KeyCode.UP)) {
select(selectionIndex <= 0 ? 0 : selectionIndex - 1);
}
if (event.getCode().equals(KeyCode.DOWN)) {
String[] lines = textArea.getText().split("\n");
select(selectionIndex >= lines.length - 1 ? lines.length - 1 : selectionIndex + 1);
}
});
rootPane.getChildren().add(textArea);
Scene scene = new Scene(rootPane, 900, 500);
primaryStage.setScene(scene);
primaryStage.show();
System.out.println("Created window.");
System.out.println("\nNow press up and down keys to navigate:\n"
+ "Notice, that although a new selection is displayed in the console, it is not\n"
+ "highlighted in the window itself. Even a call to getSelectedText() works fine.\n");
}
/**
* Creates a bunch of random options in textArea.
* @param newOptionCount
*/
private static void createRandomOptions(int newOptionCount) {
for (int i = 0; i < newOptionCount; i++) {
textArea.appendText("\nSEL" + (new Random().nextInt(10000)));
}
}
private static void select(int newSelectionIndex) {
String[] lines = textArea.getText().split("\n");
System.out.println("New selection index: " + newSelectionIndex);
selectionIndex = newSelectionIndex;
// Determine selection indexes
int selectionStart = 0;
int selectionEnd = 0;
for (int i = 0; i < newSelectionIndex; i++) {
selectionStart += lines[i].length() + 1;
}
selectionEnd = selectionStart + lines[newSelectionIndex].length();
// Does not work. Selection does need to be applied twice by the user to be actually highlighted.
textArea.selectRange(selectionStart, selectionEnd);
System.out.println("Selected text: " + textArea.getSelectedText() + "\n");
}
}
我知道它看起来很乱,也不是很干净,但你应该明白这一点.
现在的问题是:
当我使用箭头键(特别是向上和向下)在TextArea
中导航时,只有当用户应用两次 Select (仅在最上面和最下面)时, Select 才变得可见,尽管每次都会调用selectRange()
.
这是为什么?这是JavaFX库中的一个错误,还是我遗漏了什么?
我已经搜索了这个问题几次,但还没有找到任何结果. 我还没有使用AWT Swing测试这一点,但我非常有信心,使用它会工作得很好.
我的Java是带有JavaFX版本19的OpenJDK 19.