将焦点设置到文本字段 [英] Setting the focus to a text field

查看:33
本文介绍了将焦点设置到文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 netbeans 开发的应用程序,我想在显示面板时将焦点设置到某个 jTextField.我已经阅读了许多帖子并尝试了各种方法,但都没有奏效.主要问题之一是在哪里放置所需的代码,我相信在我的情况下是 this.txtMessage.requestFocusInWindow();

I have an application developed in netbeans and I want to set the focus to a certain jTextField when a panel is displayed. I have read a number of post and have tried various methods but non have worked. One of the main issues is where to place the required code, which I believe in my case is this.txtMessage.requestFocusInWindow();

有一些帖子表明使用窗口侦听器,但是由于 netbeans 生成了 GUI,我无法看到如何实现接口,因为我无法编辑创建 jPANEL 等的代码.整个事情非常令人沮丧,我真不相信这应该有那么难.

There are some posts that indicate using a Window Listener, however as netbeans has generated the GUI, I cannot see how to implement the interfaces as I cannot edit the code that creates the jPANEL etc. The whole thing is very frustrating and I really do not believe that this should be that difficult.

作为测试,我将 requestFocusInWindow(); 添加到面板上的按钮,它确实将焦点设置为所需的输入.

Just as a test I added the requestFocusInWindow(); to a button on the panel and it did set the focus to the desired input.

推荐答案

我遇到过类似的情况,我需要在面板显示时将焦点设置在面板内的文本框上.该面板是在应用程序启动时加载的,所以我无法在构造函数中设置焦点.由于面板没有被加载或被赋予焦点显示,这意味着我没有触发焦点请求的事件.

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

为了解决这个问题,我在 main 中添加了一个全局方法,该方法调用面板中的一个方法,该方法在文本区域调用 requestFocusInWindow().我把对全局方法的调用放在显示面板的按钮中,显示调用之后.这意味着将显示面板,然后在显示面板后文本区域分配焦点.希望有意义并有所帮助!

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

此外,您可以通过在设计视图中右键单击对象并选择自定义代码来编辑大部分自动生成的代码,但是我认为它不允许您编辑面板.

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

这篇关于将焦点设置到文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆