java - jTextFields 请求焦点(如果在丢失焦点后为空)不起作用

标签 java swing user-interface focus

我有 2 个 jTextFields,并且都有lostFocus 事件的监听器,如果第一个文本字段失去焦点并且为空,我希望它重新获得焦点,第二个字段几乎相同。 我试过这个:

String str = MyTextField.getText();
if (str.isEmpty()) 
    MyTextField.requestFocusInWindow();
else ...

它一开始有效,但现在即使第一个文本字段为空,第二个文本字段也获得焦点,之后一切都挂起,我认为可能存在一些并发问题...请解释原因并帮助我找到解决方案

最佳答案

使用InputVerifier

来自 javadocs,

A component's input verifier is consulted whenever the component is about to lose the focus. If the component's value is not acceptable, the input verifier can take appropriate action, such as refusing to yield the focus on the component or replacing the user's input with the last valid value and then allowing the focus to transfer to the next component. However, InputVerifier is not called when the focus is transferred to another toplevel component.

这是一个基于您的示例代码,如果文本字段为空,它会阻止按 Tab 键切换到其他文本字段

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

public class FoucsDemo
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new FoucsDemo();
            }
        });

    }

    FoucsDemo()
    {
        JFrame jFrame=new JFrame("Input Verifier");
        jFrame.setLayout(new GridLayout(2,1,1,5));
        JTextField jTextField1=new JTextField(10);
        JTextField jTextField2=new JTextField(10);
        jTextField1.setInputVerifier(new Verify());
        jTextField2.setInputVerifier(new Verify());
        jFrame.add(jTextField1);
        jFrame.add(jTextField2);
        jFrame.pack();
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    class Verify extends InputVerifier
    {
        @Override
        public boolean verify(JComponent input)
        {
            return !((JTextField) input).getText().equals("");
        }
    }
}

关于java - jTextFields 请求焦点(如果在丢失焦点后为空)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16422465/

相关文章:

java - 从数据库崩溃中检索数据

java - 让 JComponent 耗尽 JPanel 中的剩余宽度

user-interface - Qt 扩展支持吗

java - 让用户将节点添加到 JTree,如果父级曾经被扩展,则节点不会出现

java - 是什么导致 SAXException2 : Instance of “com.foo.Bar” is substituting “java.lang.Object” , 但 “com.foo.Bar” 绑定(bind)到匿名类型

java - 如何让 Weblogic 10 更喜欢 myApp.war :/WEB-INF/lib/without throwing VerifyErrors? 中的 jar

java - 使用 Java GroupLayout 定位

java - 当玩家第二次尝试时会攻击两次

java - 如何刷新 JFrame

java - ActionListener 中的 setProperty