Wednesday, 7 January 2015

Validated TextBox


// TextField which can contain only "numeric values" along with '+' or '-' at beginning (if used) and '.' at just one place.





import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


class FormattedTextBox extends JFrame implements KeyListener{
private JLabel lbltext;
private JTextField txtNum;

public FormattedTextBox(String title){
super(title);
setLayout(new GridLayout(1,1));
setSize(300,100);
              init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void init(){
lbltext=new JLabel("Enter Value : ");
add(lbltext);
txtNum = new JTextField(" ",10);
add(txtNum);
txtNum.addKeyListener(this);
}

public void keyPressed(KeyEvent ke){}
public void keyReleased(KeyEvent ke){}

public void keyTyped(KeyEvent ke){
char c = ke.getKeyChar();
int dot=txtNum.getText().indexOf(".");
int plus=txtNum.getText().indexOf("+");
int minus=txtNum.getText().indexOf("-");

if(txtNum.getCaretPosition()==0){

if(plus==-1&&minus==-1&&dot==-1){
if(!(c == '+' || c =='-' || Character.isDigit(c) || c=='.')) {
                                   ke.consume();        
                            }
}

else if(dot!=-1&&minus==-1&&plus==-1){
if(!(c == '+' || c =='-' || Character.isDigit(c))) {
                                   ke.consume();        
                            }
}

else if(plus!=-1||minus!=-1){
ke.consume();        
                     }
}

else {
if(dot==-1){
if(!(Character.isDigit(c) || c=='.')) {
                                   ke.consume();
                          }
}
else{
if(!(Character.isDigit(c))) {
                                     ke.consume();
                          }
}
}    
     }
 
public static void main (String[] args) {
FormattedTextBox ft=new FormattedTextBox("HELLO");

}
}








No comments:

Post a Comment