java - 如何取消焦点 JTextField

标签 java swing netbeans focus jtextfield

当我的应用程序加载时,它是使用 netbeans 制作的,第一个 JTextField 自动获得焦点,在这个 JTextField 中,我写了“输入您的用户名”,当用户点击这个字段时它会消失,但是当应用程序已加载,此字段已聚焦,意味着我看不到“输入您的用户名”,如何在启动时取消聚焦?

最佳答案

登录最好在模态对话框中完成,但这会引入问题,因为必须在组件可见后 调用方法 requestFocusInWindow(),但这被对话框是模态的事实所阻止!

此示例使用 Rob Camick 的 RequestFocusListener(如 Dialog Focus 中所示)在对话框可见后管理焦点。

Login with focused password field

注意:这是用户执行任何操作之前的显示方式。默认情况下,密码字段是聚焦的。

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class LoginRequired {

    LoginRequired() {
        JFrame f = new JFrame("Login Required");
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        f.setResizable(false);
        f.setSize(400, 300); // not recommended, but used here for convenience
        f.setLocationByPlatform(true);
        f.setVisible(true);

        showLogin(f);
    }

    private void showLogin(JFrame frame) {
        JPanel p = new JPanel(new BorderLayout(5,5));

        JPanel labels = new JPanel(new GridLayout(0,1,2,2));
        labels.add(new JLabel("User Name", SwingConstants.TRAILING));
        labels.add(new JLabel("Password", SwingConstants.TRAILING));
        p.add(labels, BorderLayout.LINE_START);

        JPanel controls = new JPanel(new GridLayout(0,1,2,2));
        JTextField username = new JTextField("Joe Blogs");
        controls.add(username);
        JPasswordField password = new JPasswordField();
        password.addAncestorListener(new RequestFocusListener(false));
        controls.add(password);
        p.add(controls, BorderLayout.CENTER);

        JOptionPane.showMessageDialog(
            frame, p, "Log In", JOptionPane.QUESTION_MESSAGE);
        System.out.println("User Name: " + username.getText());
        System.out.println("Password: " + new String(password.getPassword()));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginRequired();
        });
    }
}

/**
 *  Convenience class to request focus on a component.
 *
 *  When the component is added to a realized Window then component will
 *  request focus immediately, since the ancestorAdded event is fired
 *  immediately.
 *
 *  When the component is added to a non realized Window, then the focus
 *  request will be made once the window is realized, since the
 *  ancestorAdded event will not be fired until then.
 *
 *  Using the default constructor will cause the listener to be removed
 *  from the component once the AncestorEvent is generated. A second constructor
 *  allows you to specify a boolean value of false to prevent the
 *  AncestorListener from being removed when the event is generated. This will
 *  allow you to reuse the listener each time the event is generated.
 */
class RequestFocusListener implements AncestorListener
{
    private boolean removeListener;

    /*
     *  Convenience constructor. The listener is only used once and then it is
     *  removed from the component.
     */
    public RequestFocusListener()
    {
        this(true);
    }

    /*
     *  Constructor that controls whether this listen can be used once or
     *  multiple times.
     *
     *  @param removeListener when true this listener is only invoked once
     *                        otherwise it can be invoked multiple times.
     */
    public RequestFocusListener(boolean removeListener)
    {
        this.removeListener = removeListener;
    }

    @Override
    public void ancestorAdded(AncestorEvent e)
    {
        JComponent component = e.getComponent();
        component.requestFocusInWindow();

        if (removeListener)
            component.removeAncestorListener( this );
    }

    @Override
    public void ancestorMoved(AncestorEvent e) {}

    @Override
    public void ancestorRemoved(AncestorEvent e) {}
}

关于java - 如何取消焦点 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10773132/

相关文章:

java - Spring Security - 具有 IS_AUTHENTICATED_ANONYMOUSLY 但仍指定(且未知)凭据的 Url 被框架阻止

java - Swing:布局管理器与上层布局管理器的正确交互?

java - MouseEntered 事件调用每个附近的标签

java - 为什么我无法使 setSelectedIndex 工作?

java - Netbeans - 在 jComboBox 中输入项目

android - 找不到 build.xml (Android)

java - 从 4GB 文件创建 trie (JSON) 的最快方法,仅使用 1GB 内存?

java - 树单元渲染器 : applying different style of the node's text which is depending on the user object's type

Java Swing : select text cross multiple textareas

java - 如果 Swing 组件不在 NetBeans javafx 调色板中,则在 javafx 中使用它们