如何取消 JTextField 的焦点

13

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


有两个JTextFields,第一个用于用户名,第二个用于密码,还有一个名为“登录”的JMenuItem。当我运行应用程序时,第一个JTextField会自动聚焦,但我不想要这个。 - Ali Bassam
顺便提一下 - 如果每个应用程序安装的用户名预计是恒定的,请使用默认值填充用户名字段,让用户在正确时切换到下一个字段。如果保证用户名是恒定的,请填充该字段并禁用它。它将无法获得焦点,并且默认情况下焦点将转移到第二个字段。 - Andrew Thompson
4个回答

14

最好在模态对话框中进行登录,但这会带来一些问题,因为方法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) {}
}

@AloneInTheDark 这是一个独立的问题,应该在另一个问题上提出。 - Andrew Thompson

5
textField.setFocusable(false);
textField.setFocusable(true);

只有当textField拥有焦点时,TAB顺序中的下一个组件才会自动获得焦点。其效果与按下TAB键相同。

(在仅有一个可聚焦组件的GUI中未经测试 :))


4
使用requestFocusInWindow()可以将焦点设置在其他组件上,而不是您的JTextfield

但我建议不要更改本机焦点系统,而是在constructor中的initComponents()调用后使用setText(String s)JTextField上(假设在netbeans中)。

更多可选阅读:如何使用焦点子系统


如果我必须点击JMenuItem才能登录怎么办?我在另一个元素上使用了requestFocusInWindow(),但是当我点击那个JMenuItem时,JTextField会获得焦点。第二次我点击那个JMenuItem时,JTextField没有获得焦点,稍后它可以工作,但是第一次不行。 - Ali Bassam
你是否尝试在NetBeans属性编辑器中使用nextFocusableComponent属性来设置你的JMenuItem - Asif
我已经修复了,我使用了您的代码两次,一次是在启动时,另一次是当我点击Jmenuitem时,谢谢。 - Ali Bassam

4

我认为如果用户名是用户需要首先输入的内容,那么将键盘焦点放在用户名字段上是正确的行为。不要在焦点聚集时清空该字段,而是在用户输入内容后再进行清空操作:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.Document;

public class PlaceholderTextField extends JTextField {

    public static void main(final String[] args) {
        final PlaceholderTextField tf = new PlaceholderTextField("");
        tf.setColumns(20);
        tf.setPlaceholder("All your base are belong to us!");
        final Font f = tf.getFont();
        tf.setFont(new Font(f.getName(), f.getStyle(), 30));
        JOptionPane.showMessageDialog(null, tf);
    }

    private String placeholder;

    public PlaceholderTextField() {
    }

    public PlaceholderTextField(
        final Document pDoc,
        final String pText,
        final int pColumns)
    {
        super(pDoc, pText, pColumns);
    }

    public PlaceholderTextField(final int pColumns) {
        super(pColumns);
    }

    public PlaceholderTextField(final String pText) {
        super(pText);
    }

    public PlaceholderTextField(final String pText, final int pColumns) {
        super(pText, pColumns);
    }

    public String getPlaceholder() {
        return placeholder;
    }

    @Override
    protected void paintComponent(final Graphics pG) {
        super.paintComponent(pG);

        if (placeholder.length() == 0 || getText().length() > 0) {
            return;
        }

        final Graphics2D g = (Graphics2D) pG;
        g.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(getDisabledTextColor());
        g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
            .getMaxAscent() + getInsets().top);
    }

    public void setPlaceholder(final String s) {
        placeholder = s;
    }

}

如果您只想取消焦点,有以下几个选项:

  • component.setFocusable(false);
  • KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
  • KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接