-1

Suppose I have a JDialog with 3 text fields First, Last and LastFirst. When LastFirstreceives the focus it is to be set as the concatenation of first & last, but only if first & last are not empty. Here's pertinent code from my example, which doesn't work: What am I missing?

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);
}
});
}
}
Ed S
  • 239
  • 5
  • 21
  • 1
    `"What am I missing?"` -- it would help greatly if you created and posted a valid [mcve], a small but complete program that only has necessary code to demonstrate your problem, that we can copy, paste, compile and run without modification, as this would help us to fully understand what you might be doing wrong. Note that this is code posted as code-formatted text and not as a link to an off-site resource. – Hovercraft Full Of Eels Jun 16 '16 at 18:57
  • Maybe use a `FocusListener` and a `PropertyChangeListener`, for [example](http://stackoverflow.com/a/8703807/230513). – trashgod Jun 16 '16 at 22:37

1 Answers1

0

My mistake was issuing the txtFirst.requestFocusInWindow() AFTER the showMessageDialog. Moving it to BEFORE the showMessageDialog fixes the problem.

Apparently, when it's before the focus is regained by LastFirst causing the message again, but by that time the focus has been reset to First. Hard to explain, but the answer is clearly to requestFocus first, then issue the message.

Ed S
  • 239
  • 5
  • 21