Last active
January 2, 2016 15:59
-
-
Save fahri007/8326890 to your computer and use it in GitHub Desktop.
Membuat validasi di JTextfield sehingga cuma dapat menerima inpu Integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package incl; | |
import javax.swing.JTextField; | |
import javax.swing.text.AttributeSet; | |
import javax.swing.text.BadLocationException; | |
import javax.swing.text.Document; | |
import javax.swing.text.PlainDocument; | |
/** | |
* A JTextField that accepts only integers. | |
* | |
* @author David Buzatto | |
*/ | |
public class IntegerField extends JTextField { | |
public IntegerField() { | |
super(); | |
} | |
public IntegerField( int cols ) { | |
super( cols ); | |
} | |
@Override | |
protected Document createDefaultModel() { | |
return new UpperCaseDocument(); | |
} | |
static class UpperCaseDocument extends PlainDocument { | |
@Override | |
public void insertString( int offs, String str, AttributeSet a ) | |
throws BadLocationException { | |
if ( str == null ) { | |
return; | |
} | |
char[] chars = str.toCharArray(); | |
boolean ok = true; | |
for ( int i = 0; i < chars.length; i++ ) { | |
try { | |
Integer.parseInt( String.valueOf( chars[i] ) ); | |
} catch ( NumberFormatException exc ) { | |
ok = false; | |
break; | |
} | |
} | |
if ( ok ) | |
super.insertString( offs, new String( chars ), a ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment