【问题标题】:How do you set a focus on JTextField in Swing?如何在 Swing 中将焦点放在 JTextField 上?
【发布时间】:2009-09-15 06:03:37
【问题描述】:

我在 Java 中使用 Swing 创建了一个表单。在表单中,我使用了JTextField,每当我按下一个键时,我都必须在它上面设置焦点。如何在 Swing 中设置对特定组件的关注?

【问题讨论】:

    标签: java swing focus


    【解决方案1】:

    Component.requestFocus() 会给你你需要的吗?

    【讨论】:

    【解决方案2】:

    这行得通..

    SwingUtilities.invokeLater( new Runnable() { 
    
    public void run() { 
            Component.requestFocus(); 
        } 
    } );
    

    【讨论】:

    • 这个对我有用,不像其他的,特别是因为我在我的应用程序中从一个屏幕切换到另一个屏幕,并在新屏幕打开时请求焦点。
    【解决方案3】:

    现在我们已经搜索了 API,我们需要做的就是阅读 API。

    根据 API 文档:

    "因为这个的焦点行为 方法依赖于平台, 强烈建议开发人员 使用 requestFocusInWindow 时 可能的。 "

    【讨论】:

      【解决方案4】:

      请注意,由于某种原因,上述所有操作在 JOptionPane 中都失败了。经过多次试验和错误(无论如何,超过上述 5 分钟),这就是最终奏效的方法:

              final JTextField usernameField = new JTextField();
      // ...
              usernameField.addAncestorListener(new RequestFocusListener());
              JOptionPane.showOptionDialog(this, panel, "Credentials", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
      
      
      public class RequestFocusListener implements AncestorListener {
          @Override
          public void ancestorAdded(final AncestorEvent e) {
              final AncestorListener al = this;
              SwingUtilities.invokeLater(new Runnable() {
      
                  @Override
                  public void run() {
                      final JComponent component = e.getComponent();
                      component.requestFocusInWindow();
                      component.removeAncestorListener(al);
                  }
              });
          }
      
          @Override
          public void ancestorMoved(final AncestorEvent e) {
          }
      
          @Override
          public void ancestorRemoved(final AncestorEvent e) {
          }
      }
      

      【讨论】:

        【解决方案5】:

        你也可以用JComponent.grabFocus();也一样

        【讨论】:

        • Javadoc for JComponent.grabFocus() 明确指出客户端代码不应使用此方法,并建议使用 requestFocusInWindow() 方法,该方法已在其他答案中提及。
        猜你喜欢
        • 2017-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        相关资源
        最近更新 更多