---
title: "关于Jtextinpt 内容的限制"
author: "yaoweinan"
date: "2012-09-28T15:00:29Z"
tags: []
categories: ["编程语言"]
slug: "jtextinpt"
draft: false
lastmod: "2012-09-28T15:00:29Z"
id: 1688011
url: "https://ilyon.iteye.com/blog/1688011"
---

在JTextInput 限制输入内容，这个一般的通过按键输入进行检查，如果输入的内容不是你想要的就取消输入，但是如果有人进行了黏贴就挂掉了，彻底完蛋，下面写了个简单的例子，抛砖引玉：

 

 

```
/*
 * @(#) Test1.java Sep 28, 2012 1:35:40 PM
 *
 * Copyright 2012 Rockwell Automation, Inc. All rights reserved.
 * Rockwell Automation PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */package com.my.study;

import java.awt.Dimension;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class Test1 extends JFrame {

  /**
   * @param args
   */
  public static void main(String[] args) {
    new Test1();
  }
  Test1(){
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    this.setSize(new Dimension(100,100));
    JTextField field=new JTextField();
    field.setDocument(new PlainDocument(){

      @Override
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        Pattern pattern = Pattern.compile("\\d");
        Matcher matcher = pattern.matcher(str);
        if(!matcher.find()){
          return;
        }
        
        super.insertString(offs, str, a);
      }
      
    });
    this.add(field);
    this.setVisible(true);
    
  }
}
```

 

之后你可以在这个inserString 中干一番大事业 .....