有没有办法把焦点放在javafx上?

我知道你可以通过执行node.requestFocus();将焦点放在javafx中的节点上 但有没有办法从javafx中的节点中取走焦点或防止对焦于对象?

我不认为有任何保证会一直有效,但您可以尝试将焦点设置为本身不接受键盘输入的内容(例如布局窗格):

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class NoFocusTest extends Application { @Override public void start(Stage primaryStage) { TextField tf1 = new TextField(); tf1.setPromptText("Enter something"); TextField tf2 = new TextField(); tf2.setPromptText("Enter something else"); VBox root = new VBox(5, tf1, tf2); primaryStage.setScene(new Scene(root, 250, 150)); primaryStage.show(); root.requestFocus(); } } 
 node = new node() { public void requestFocus() { } }; 

现在这将覆盖焦点,节点永远不会有焦点。 您也可以(如前所述)禁用节点:

 node.setDisable(true); 

如果您以后需要关注:

 node.setDisable(false); node.requestFocus(); 

我决定用另外一个选项更新我对此的回答。 如果您在程序开始时给予另一个节点焦点,则可以将特定节点设置为不可遍历,并且不会获得焦点。

 node.setFocusTraversible(false); 

如果您有另一个节点,那么您可以从节点中删除焦点并将其提供给另一个节点。

 otherNode.requestFocus(); 

通过执行此操作,您无需禁用或启用原始节点。

某些节点(如Label)在具有焦点时看起来不会有所不同,因此可以使其看起来好像已移除焦点。