Thursday, 5 February 2015

Using FormattedTextFields and PasswordFields in java

//A program to understnad the formatted text field of java and to use a passwordField
// Enter the values in the textfields to understand this problem better.




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

class FormattedTextBoxDemo extends JFrame implements ActionListener{
private JFormattedTextField txt_amount,txt_currency,txt_number;
private JPasswordField psw;
private JLabel lbl;
private NumberFormat model;
private JButton btn;

public FormattedTextBoxDemo(String title){
super(title);
setLayout(new GridLayout(5,2));
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

lbl = new JLabel("Total Amount :");
add(lbl);
// Declare the type of model to be used in the textfield

// getNumberInsatance model allows you to enter only number values in the textfield.
model = NumberFormat.getNumberInstance();
txt_amount = new JFormattedTextField(model);
txt_amount.setColumns(10);
add(txt_amount);

lbl = new JLabel("Currency :");
add(lbl);
// getCurencyInsatance model allows you to enter the values in Currency format as Rs.1200
// without the currency the value will not be proccesed by the textfield.
model = NumberFormat.getCurrencyInstance();
txt_currency= new JFormattedTextField(model);
txt_currency.setColumns(10);
add(txt_currency);


lbl = new JLabel("Number of Currency Notes :");
add(lbl);
// getIntegerInsatnce model allows to enter only an integer value i.e. fraction values are not allowed.
model = NumberFormat.getIntegerInstance();
txt_number= new JFormattedTextField(model);
txt_number.setColumns(10);
add(txt_number);

lbl = new JLabel("Password :");
add(lbl);
// This field will show the text inside the field as '*' i.e.hidden
psw = new JPasswordField();
add(psw);

btn = new JButton("Click ME");
btn.addActionListener(this);
add(btn);


lbl = new JLabel();
add(lbl);
pack();

}

public void actionPerformed(ActionEvent e){

lbl.setText("Your Password is :  " + psw.getText());



}

public static void main (String[] args) {
new FormattedTextBoxDemo("Formatted Text Field Demo");
}
}

No comments:

Post a Comment