有没有办法在javafx中消除焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25431959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to take away focus in javafx?
提问by sazzy4o
I know that your can give focus to a node in javafx by doing node.requestFocus();but is there a way to take away focus from a node in javafx or prevent focus on an object?
我知道您可以通过执行node.requestFocus();将焦点放在 javafx 中的节点上;但是有没有办法从 javafx 中的节点上拿走焦点或防止焦点放在对象上?
采纳答案by James_D
I don't think there's any guarantee this will always work, but you can try setting focus to something that inherently doesn't accept keyboard input (such as a layout pane):
我不认为有任何保证这将始终有效,但是您可以尝试将焦点设置为本质上不接受键盘输入的内容(例如布局窗格):
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();
}
}
回答by Philip Vaughn
node = new node() {
public void requestFocus() { }
};
Now this will override the focus and the node will NEVER be able to have focus. You could also (as stated before) disable the node with:
现在这将覆盖焦点,节点将永远无法获得焦点。您还可以(如前所述)使用以下命令禁用节点:
node.setDisable(true);
If you need focus later:
如果您稍后需要专注:
node.setDisable(false);
node.requestFocus();
I decided to update my answer to this with one more option. If you are giving another node focus at the start of the program you could set a particular node to be non-traversable and it will not gain focus.
我决定用另一个选项更新我的答案。如果您在程序开始时给予另一个节点焦点,您可以将特定节点设置为不可遍历,并且它不会获得焦点。
node.setFocusTraversable(false);
回答by GreenMachine
If you have another node then you can remove focus from your node and give it to another with this.
如果您有另一个节点,那么您可以从您的节点中移除焦点并将其交给另一个节点。
otherNode.requestFocus();
By doing this you won't need to disable or enable your original node.
通过这样做,您不需要禁用或启用您的原始节点。
Some nodes such as a Label won't look different when they have focus, so this can make it appear as if focus was removed.
某些节点(例如 Label)在获得焦点时看起来不会有所不同,因此这可以使其看起来好像焦点已被移除。