Following the Question Synchronize JTextField values by property change listener
I have tried to modify the example from the answer using document listener. What I wanted to modify was to synchronize only integers. For example, if I put '2' in field1 then it would multiply by '5' so that the value would be '10' in the field2. However, I have followed various methods but I am having some errors such as:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Moreover, when I delete all values from field1, the last synchronized field2 value remains whereas field2 also supposed to be null as field1. I am not sure which part I have made mistake. Here is my code sample for the UpdateLabel Method:
private void updateLabel(DocumentEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
String text = field.getText();
String text1 = field1.getText();
@Override
public void run() {
if(text == null && text1 != null){field1.setText(null);
}else
if(text.contains("-") ||
text.contains(".") ||
text.matches(".*[a-zA-Z].*")||
text.matches(".*\\p{Punct}.*")){
{JOptionPane.showMessageDialog(frame = new JFrame(),
"Please put appropriate int value from 0-9",
"Inane error",
JOptionPane.ERROR_MESSAGE);
field.setText(null);
field1.setText(null);
}
}else{
int p;
p = Integer.parseInt(text);
int i = (p*5);
String s = String.valueOf(i);
field1.setText(s);
}
}
});
}
I also want to use the '.' with integers but when I removetext.contains(".")
it still shows JOptionPane
error message.