Friday, September 26, 2014

how to create a textfield that holds only upper case characters in java?





 The following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard.


 UpperCaseField.java

import javax.swing.*;

import javax.swing.text.Document;

import javax.swing.text.PlainDocument;

import javax.swing.text.AttributeSet;

import javax.swing.text.BadLocationException;



public class UpperCaseField extends JTextField {



     public UpperCaseField(int cols) {

         super(cols);

     }



     protected Document createDefaultModel() {

         return new UpperCaseDocument();

     }



     static class UpperCaseDocument extends PlainDocument {



         public void insertString(int offs, String str, AttributeSet a)

             throws BadLocationException {



             if (str == null) {

                 return;

             }

             char[] upper = str.toCharArray();

             for (int i = 0; i < upper.length; i++) {

                 upper[i] = Character.toUpperCase(upper[i]);

             }

             super.insertString(offs, new String(upper), a);

         }

     }



 }




main.java


import javax.swing.*;

import java.awt.*;



class main extends JFrame

{

UpperCaseField ucf;

Container c;

main()

{

c=getContentPane();

c.setLayout(null);

setTitle("Text");

setBounds(120,100,500,350);

setVisible(true);

setResizable(false);

JLabel lbl=new JLabel("Upper Case:");

lbl.setBounds(10,10,100,30);

c.add(lbl);

ucf=new UpperCaseField(30);

ucf.setBounds(120,10,350,30);

c.add(ucf);

setContentPane(c);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main(String[] arg)

{

 new main();

}



}



OUTPUT:-