有一个文本字段,当失去焦点时,它将验证输入,如果未通过,则打印出错误消息(简单来说这里只有一个空检查)。文本字段旁边有一个按钮,单击它会打印出文本。
正如我所尝试的,当输入一些文本然后单击按钮时,它将触发文本字段的焦点丢失事件和按钮事件。换句话说,它将首先进行验证,然后打印出输入文本。
我的问题来了,如果验证未通过,防止打印出文本的好方法是什么?或者如果验证未通过,有没有办法“忽略”按钮上的点击事件?
我尝试使用指示验证结果的布尔标志并在执行按钮操作时检查标志,但我认为这不是一个好方法。我知道 Swing 中有一个事件调度程序线程处理事件,我可以从这里取消事件吗?
下面是一段解释问题的代码:
public class SimpleDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel(new FlowLayout());
frame.setContentPane(content);
final JTextField textField = new JTextField(10);
textField.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent e)
{
String text = textField.getText();
// do some validation here, if not validated
// do not trigger the event on button.
if ("".equals(text))
{
System.out.print("please input a text!");
}
}
});
content.add(textField);
JButton button = new JButton("Print Text");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// action performed for button
String text = textField.getText();
System.out.println(text);
}
});
content.add(button);
frame.setVisible(true);
frame.pack();
}
}