根据经过验证的其他字段设置字段

时间:2016-06-16 18:55:32

标签: java swing validation focus

假设我有一个JDialog,包含3个文本字段First,Last和LastFirst。当LastFirst收到焦点时,它将被设置为first&的串联。最后,但只有在第一个&最后不是空的。以下是我的示例中的相关代码,它不起作用: 我错过了什么?

import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
public class FieldValidatedSetting extends javax.swing.JFrame {
private javax.swing.JTextField txtFirst;
private javax.swing.JTextField txtLast;
private javax.swing.JTextField txtLastFirst;
// 
//This is supposed to concatenate Last & First and set LastFirst. 
// Empty   First or Last fields should result in a message dialog
// and return for user correction. Problem is it issues the message twice!
// Please excuse the crummy layout./
// Constructor  
private void txtLastFirstFocusGained(java.awt.event.FocusEvent evt)                                              
if(txtLast.getText().isEmpty() || txtFirst.getText().isEmpty()){
        JOptionPane.showMessageDialog(null, "You must enter First & Last");
        txtFirst.requestFocusInWindow();
    } else{
        txtLastFirst.setText(txtLast.getText()  +  txtFirst.getText());
    }
}             

public FieldValidatedSetting() {
txtFirst = new javax.swing.JTextField();
txtLast = new javax.swing.JTextField();
txtLastFirst = new javax.swing.JTextField();

txtLastFirst.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
            txtLastFirstFocusGained(evt);
}
});
Container pane = getContentPane();
pane.setLayout(new GridLayout(1, 3));
pane.add(txtFirst);
pane.add(txtLast);
pane.add(txtLastFirst);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FieldValidatedSetting().setVisible(true);
}
});
}
}

1 个答案:

答案 0 :(得分:0)

我的错误是在showMessageDialog之后发出了txtFirst.requestFocusInWindow()。将它移到showMessageDialog之前修复问题。

显然,在LastFirst重新获得焦点之前,再次导致消息,但到那时焦点已重置为First。很难解释,但答案显然是先请求焦点,然后发出消息。