Duplicate :
|
FULL PRODUCT VERSION : java version "1.4.2_08" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03) Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode) ADDITIONAL OS VERSION INFORMATION : Microsoft Windows XP Version 2002 A DESCRIPTION OF THE PROBLEM : I have designed a GUI, where I take inputs from a textField. I have to validate the input values in a JTextField in focusLost event. If the input in the JTextField is incorrect I show an error message to the user (I am using JOptionPane) and put the focus back to the JTextField. Result Observed: The the error message is showing multiple times. After debugging I found that the focusLost Event is triggered multiple times for the grabFocus of the text field. REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- import java.awt.event.FocusEvent; import javax.swing.JOptionPane; import javax.swing.JTextField; public class NewJFrame extends javax.swing.JFrame { /** Creates new form NewJFrame */ public NewJFrame() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code "> private void initComponents() { jTextField1 = new javax.swing.JTextField(); jCheckBox1 = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setText("jTextField1"); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTextField1FocusLost(evt); } }); getContentPane().add(jTextField1, java.awt.BorderLayout.SOUTH); jCheckBox1.setText("jCheckBox1"); jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0)); getContentPane().add(jCheckBox1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold> private void jTextField1FocusLost(java.awt.event.FocusEvent evt) { focusLost(evt); } public void focusLost(FocusEvent e){ Object obj = e.getSource(); JTextField textField = new JTextField(); if (textField instanceof JTextField) { textField = (JTextField) obj; String value = textField.getText(); try { Integer.parseInt(value); } catch (NumberFormatException ex) { System.out.println("User entered wrong value"); JOptionPane.showMessageDialog(jTextField1, "Please enter a numeric value", "Error", JOptionPane.ERROR_MESSAGE); textField.setText(""); textField.grabFocus(); return; } } } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JCheckBox jCheckBox1; private javax.swing.JTextField jTextField1; // End of variables declaration } ---------- END SOURCE ----------