⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 numerictextfield.java

📁 < ProJavaProgrammingSecondEdition> 书中例程源码
💻 JAVA
字号:
import javax.swing.*;
import javax.swing.text.*;

public class NumericTextField extends JTextField {

  protected boolean allowDecimal;

  public NumericTextField(int size, boolean decimal) {
    super(size);
    setDocument(new NumericDocument());
    allowDecimal = decimal;
  }

  class NumericDocument extends PlainDocument {

    public void insertString(int offset, String text, AttributeSet as)
        throws BadLocationException {
      if (isInsertAllowed(offset, text)) {
        super.insertString(offset, text, as);
      }
    }

    protected boolean isInsertAllowed(int offset,
        String text) throws BadLocationException {
      boolean allowed = true;
      int length = getLength();
      String current = getText(0, length);
      String before = current.substring(0, offset);
      String after = current.substring(offset);
      String newText = before + text + after;
      try {
        if (allowDecimal) {
          Double d = Double.valueOf(newText);
        }
        else {
          Integer.parseInt(newText);
        }
      } catch (NumberFormatException nfe) {
        allowed = false;
      }
      return allowed;
    }

  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -