Java 在 JTextField 上设置光标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18908902/
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
Set Cursor On A JTextField
提问by Zenith Blade
I am making a small application in Java that uses a JTextField. Now, I want, as soon as I run the app, the cursor to be put automatically in that so that the user doesn't have to click on it and then write the text. I have tried pretty much everything that I found on the net: setCaretPosition(0), grabFocus(), requestFocusInWindow() or requestFocus() but none of them worked! I am desperate, can you please help me solve this? Thanks a lot
我正在用 Java 制作一个使用 JTextField 的小应用程序。现在,我希望,只要我运行该应用程序,光标就会自动放入其中,这样用户就不必单击它然后编写文本。我已经尝试了我在网上找到的几乎所有东西:setCaretPosition(0)、grabFocus()、requestFocusInWindow() 或 requestFocus() 但它们都没有奏效!我很绝望,你能帮我解决这个问题吗?非常感谢
采纳答案by camickr
By default focus will go to the first component on the Window.
默认情况下,焦点将转到窗口上的第一个组件。
If the text field is not the first component then you can use:
如果文本字段不是第一个组件,那么您可以使用:
textField.requestFocusInWindow();
however you must invoke this method AFTER the window is visible.
但是,您必须在窗口可见后调用此方法。
If you want specify the component with focus before the window is visible then you can use the RequestFocusListener
approach from Dialog Focus.
如果要在窗口可见之前指定具有焦点的组件,则可以使用Dialog Focus 中的RequestFocusListener
方法。
回答by Shivam Sharma
this works properly for cursor position textField.requestFocus();
这适用于光标位置 textField.requestFocus();