
Silahkan download projectnya disini
TableHeader.rar
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author hauw
*/
public class PhoneValidator extends PlainDocument {
private int maxCharacter;
private boolean phoneOnly;
private String phoneChars = "+#*0123456789";
public PhoneValidator() {
this(-1, false);
}
public PhoneValidator(int maxCharacter, boolean phoneOnly) {
this.maxCharacter = maxCharacter;
this.phoneOnly = phoneOnly;
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (phoneOnly) {
if (maxCharacter == -1) {
if (checkString(str)) {
super.insertString(offs, str, a);
}
} else {
int panjangTextLama = getLength();
int panjangTextBaru = str.length();
if ((panjangTextLama + panjangTextBaru) <= maxCharacter) {
if (checkString(str)) {
super.insertString(offs, str, a);
}
}
}
} else {
if (maxCharacter == -1) {
super.insertString(offs, str, a);
} else {
int panjangTextLama = getLength();
int panjangTextBaru = str.length();
if ((panjangTextLama + panjangTextBaru) <= maxCharacter) {
super.insertString(offs, str, a);
}
}
}
}
private boolean checkString(String input) {
boolean result = false;
for (int i = 0; i < input.length(); i++) {
if (phoneChars.indexOf(input.charAt(i)) == -1) {
result = false;
break;
} else {
result = true;
}
}
return result;
}
}
import javax.swing.JFrame;
import javax.swing.JTextField;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author hauw
*/
public class TestValidasi {
public static void main(String[] args) {
JFrame frame = new JFrame("Test validasi text field");
JTextField textNoTelpon = new JTextField();
textNoTelpon.setDocument(new PhoneValidator(15, true));
frame.add(textNoTelpon);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}