歡迎來到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. * upper case 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 UpperCaseField extends JTextField {
  17. /**
  18. *
  19. */
  20. private static final long serialVersionUID = 6854878572763032459L;
  21. public UpperCaseField(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. for (int i = 0; i < upper.length; i++) {
  41. upper[i] = Character.toUpperCase(upper[i]);
  42. }
  43. super.insertString(offs, new String(upper), a);
  44. }
  45. }
  46. }
Copyright © Linux教程網 All Rights Reserved