歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java只允許輸入數字的文本框

Java只允許輸入數字的文本框

日期:2017/3/1 10:16:07   编辑:Linux編程

Java只允許輸入數字的文本框:

  1. package com.han;
  2. import javax.swing.JTextField;
  3. import javax.swing.text.AttributeSet;
  4. import javax.swing.text.BadLocationException;
  5. import javax.swing.text.Document;
  6. import javax.swing.text.PlainDocument;
  7. /**
  8. * Customized fields can easily be created by extending the model
  9. * and changing the default model provided. For example,
  10. * the following piece of code will create a field that holds only
  11. * digit characters. It will work even if text is pasted into from
  12. * the clipboard or it is altered via programmatic changes.
  13. * @author HAN
  14. *
  15. */
  16. public class DigitOnlyField extends JTextField {
  17. /**
  18. *
  19. */
  20. private static final long serialVersionUID = 8384787369612949227L;
  21. public DigitOnlyField(int cols) {
  22. // super() 可以被自動調用,但是有參構造方法並不能被自動調用,只能依賴
  23. // super關鍵字顯示地調用父類的構造方法
  24. super(cols);
  25. }
  26. protected Document createDefaultModel() {
  27. return new UpperCaseDocument();
  28. }
  29. static class UpperCaseDocument extends PlainDocument {
  30. /**
  31. *
  32. */
  33. private static final long serialVersionUID = -4170536906715361215L;
  34. public void insertString(int offs, String str, AttributeSet a)
  35. throws BadLocationException {
  36. if (str == null) {
  37. return;
  38. }
  39. char[] upper = str.toCharArray();
  40. String filtered = "";
  41. for (int i = 0; i < upper.length; i++) {
  42. if (Character.isDigit(Character.codePointAt(upper, i))){
  43. filtered += upper[i];
  44. }
  45. }
  46. super.insertString(offs, filtered, a);
  47. }
  48. }
  49. }
Copyright © Linux教程網 All Rights Reserved