gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:36:45 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com