我正在编写一个控制台应用程序,我想在按 Tab 键时自动完成命令。问题是当您在 javaFX 中按 Tab 键时,它会将焦点切换到应用程序中的另一个元素。有什么办法可以禁用这个吗?
添加事件过滤器并使用事件:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class DisableFocusNavigation extends Application {
private TextField createTextField() {
TextField textField = new TextField();
textField.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.TAB) {
System.out.println("Tab pressed");
event.consume();
}
});
return textField ;
}
@Override
public void start(Stage primaryStage) {
TextField tf1 = createTextField();
TextField tf2 = createTextField();
VBox root = new VBox(5, tf1, tf2);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
请注意,这不是特别好的做法,因为它使得在没有鼠标(或类似输入设备)的情况下无法使用应用程序。您至少应该检查事件过滤器中的修饰键,并允许一些焦点遍历选项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句