1. package org.jr.swing.text;
  2. /**
  3. * Copyright: Copyright (c) 2002-2004
  4. * Company: JavaResearch(http://www.javaresearch.org)
  5. * 最后更新日期:2003年2月12日
  6. * @author Cherami
  7. */
  8. import javax.swing.text.*;
  9. /**
  10. * 输入内容长度受限并且可能自动将小写输入转换为大写的Swing文档模型。
  11. * <p><b>注意:</b>本方法和0.12版相比功能发生了变化。
  12. * 现在可以控制暂时取消将小写转换为大写的功能。
  13. * @since 0.1
  14. */
  15. public class TextLenghtLimitedDocument
  16. extends PlainDocument {
  17. /**
  18. * 可以输入的最大长度。
  19. */
  20. protected int limitLength;
  21. /**
  22. * 是否将小写转换为大写。
  23. */
  24. protected boolean toUppercase = false;
  25. /**
  26. * 根据指定的最大长度构造一个TextLenghtLimitedDocument。
  27. * @param limitLength 可以输入的最大长度
  28. * @since 0.1
  29. */
  30. public TextLenghtLimitedDocument(int limitLength) {
  31. super();
  32. this.limitLength = limitLength;
  33. }
  34. /**
  35. * 根据指定的最大长度和是否进行小写自动转换标志构造一个TextLenghtLimitedDocument。
  36. * @param limitLength 可以输入的最大长度
  37. * @param upper 是否自动将小写输入转换为大写,true的时候转换,否则不转换。
  38. * @since 0.1
  39. */
  40. public TextLenghtLimitedDocument(int limitLength, boolean toUppercase) {
  41. super();
  42. this.limitLength = limitLength;
  43. this.toUppercase = toUppercase;
  44. }
  45. /**
  46. * 设置是否将小写转换为大写。
  47. * @param toUppercase 是否将小写转换为大写,true的时候进行转换,否则不转换。
  48. * @since 0.3
  49. */
  50. public void setToUppercase(boolean toUppercase) {
  51. this.toUppercase = toUppercase;
  52. }
  53. /**
  54. * 返回是否将小写转换为大写。
  55. * @return 将小写转换为大写时返回true,否则返回false。
  56. * @since 0.3
  57. */
  58. public boolean isToUppercase() {
  59. return toUppercase;
  60. }
  61. /**
  62. * 插入某些内容到文档中。
  63. * 只有当输入的内容的长度没有超过最大长度时才可以插入,超过的部分被忽略。
  64. * 设置了自动将小写转换为大写时也会进行转换。
  65. * 此方法是线程安全的。
  66. * <p><b>注意:</b>本方法和0.12版相比功能发生了变化。
  67. * 原来是如果要插入的总的内容的长度加上已有内容的长度超过限制是不插入任何新内容,
  68. * 现在修改为尽最大可能插入多的内容,多出的内容被忽略。
  69. * @param offs 插入位置的偏移量
  70. * @param str 插入内容
  71. * @param a 属性集合
  72. * @throws BadLocationException 给出的插入位置不是文档中的有效位置
  73. * @since 0.1
  74. */
  75. public void insertString
  76. (int offset, String str, AttributeSet attr) throws BadLocationException {
  77. if (str == null) {
  78. return;
  79. }
  80. if ( (getLength() + str.length()) > limitLength) {
  81. str = str.substring(0, limitLength - getLength());
  82. }
  83. if (toUppercase) {
  84. str = str.toUpperCase();
  85. }
  86. super.insertString(offset, str, attr);
  87. }
  88. }