Source Code : Validating a JTextField When Permanently Losing the Focus
Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com.
Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com.
Click Here or search from google with Libraries Name you get jar file related it
Validating a JTextField When Permanently Losing the Focus
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField component = new JTextField(10);
JTextField component1 = new JTextField(10);
component.addFocusListener(new MyFocusListener());
component1.addFocusListener(new MyFocusListener());
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.add(component1);
f.add(component);
f.pack();
f.setVisible(true);
}
}
class MyFocusListener extends FocusAdapter {
boolean showingDialog = false;
public void focusGained(FocusEvent evt) {
final JTextComponent c = (JTextComponent) evt.getSource();
String s = c.getText();
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
c.setSelectionStart(i);
c.setSelectionEnd(i);
break;
}
}
}
public void focusLost(FocusEvent evt) {
final JTextComponent c = (JTextComponent) evt.getSource();
String s = c.getText();
if (evt.isTemporary()) {
return;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
System.out.println("must only contain digits");
c.requestFocus();
break;
}
}
}
}
Thank with us