自扩展JTextField-1


 1 import  java.awt. * ;
 2 import  javax.swing. * ;
 3 import  javax.swing.text. * ;
 4 import  java.awt.event. * ;
 5
 6 public   class  TextFieldDemo  extends  JFrame
 7 {
 8      public  TextFieldDemo()
 9      {
10
11         Container contentPane =   this .getContentPane();
12
13         contentPane.setLayout( new  FlowLayout());      
14         DigitalText txtDigitalText  =   new  DigitalText( 10 , 10 );
15         contentPane.add( new  JLabel( " 文本框 " ));
16         contentPane.add(txtDigitalText);
17        
18
19         pack();
20         setVisible( true );
21         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22     }

23
24      public   static   void  main(String args[]) 
25      {
26          TextFieldDemo frame  =   new  TextFieldDemo();
27     }

28 }

29 // 用户自定义类
30 class  DigitalText  extends  JTextField 
31 {
32      int  len;
33      public  DigitalText( int  len)
34      {
35          this .len = len;
36     }

37         public  DigitalText(  int  column, int  len)
38      {
39
40          super (column);
41          this .len = len;
42     }

43      public  DigitalText(String strText,  int  column, int  len)
44      {
45          super (strText,column);
46          this .len = len;
47     }

48      protected  Document createDefaultModel()
49      {
50          return   new  DigitalTextDocument();
51     }

52     
53      class  DigitalTextDocument  extends  PlainDocument 
54      {
55          public   void  insertString(  int  offs, String str, AttributeSet  a)  throws  BadLocationException
56          {
57              if ( str  ==   null  )  return ;           
58              if (( this .getLength() + str.length()) > len)
59                 return ;
60              super .insertString(offs,str,a);
61         }

62     }

63
64 }

你可能感兴趣的:(自扩展JTextField-1)