Saturday, 28 February 2015

PhoneBook system using java

// A small project type program of phonebook system using LinkList as storage in which a user can add, update, delete and search records. Here, the records are not stored permanently. You will have to add new records afresh each time you run the program.




The default tab of the program


Adding Records in PhoneBook 


Searching and Editing the existing record
Need to click on SAVE to save the updated record


Deleting some record from the PhoneBook




Validation applied in different Textfields(as shown for Email)



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

 class Details{
private String contact_no , name;
private String email_address, address;

public Details(){}

public Details(String name,String contact,String email,String address){
putName(name);
putContact(contact);
putEmail(email);
putAddress(address);
}
public void putName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void putContact(String contact){
contact_no = contact;
}
public String getContact(){
return contact_no;
}

public void putEmail(String email){
email_address = email;
}
public String getEmail(){
return email_address;
}

public void putAddress(String address){
this.address = address;
}
public String getAddress(){
return address;
}
}


class Table{

class MyModel extends DefaultTableModel{
public MyModel(Object[] columnNames , int rowcount){
super(columnNames,rowcount);
}
public boolean isCellEditable(int row , int column){
if(column == 1)
return false;
else return true;
}
public void setValueAt(Object aValue,int row, int column){
int temp = 0;
if(column == 2){
for(int i = 0 ; i < aValue.toString().length() ; i++){
char c = aValue.toString().charAt(i);
if(i == 0){
if( !Character.isDigit(c) && ! (c == '+')){
temp++;
}
}
else{
if(!(Character.isDigit(c)) && !(c == ',') && !(c == '+')){
temp++;
}
}
}

if(temp == 0){
super.setValueAt(aValue,row,column);
}

}

else if(column == 3){
int atpos = aValue.toString().indexOf("@");
int dotpos = aValue.toString().indexOf(".");
boolean at = !(atpos > 0);
boolean dot = !(dotpos > (atpos+1));
boolean check = (dotpos == (aValue.toString().length()-1));

if( aValue.toString().trim().equals("") || at || dot || check){
temp++;
}

if(temp == 0){
super.setValueAt(aValue,row,column);
}
}
else{
super.setValueAt(aValue,row,column);
}
}
}

  JTable table;
  MyModel dm;
  String[] column_names = {"S.No.","Name","Contact No","Email Address","Address"};
 
  public Table(){
  dm  = new MyModel(column_names,0);
  table = new JTable(dm);
  table.setAutoCreateRowSorter(true);
  }

public JTable getTable(){
return table;
}

public DefaultTableModel getDm(){
return dm;
}

public void tableData(JPanel pnl){
JScrollPane scroll = new JScrollPane(table);
pnl.add(scroll,BorderLayout.CENTER);
}

public void addRecordToTable(Details temp){
int row = dm.getRowCount();
String[] rowdata = {""+ (row+1) , temp.getName() , temp.getContact() , temp.getEmail() , temp.getAddress() };
dm.insertRow(row, rowdata);
}
}


class Phonebook extends JFrame implements ActionListener{
private JTabbedPane tabbedpane;
private JPanel pnladdrecord,pnlsearch;
private JLabel lblname,lblcontact,lblemail,lbladdress,lblverification,lblstatus;
private JTextField txtname,txtcontact,txtemail,txtaddress,txtnamesearch;
private JButton btnadd,btnsearch,btndelete,btnSave;
private LinkedList<Details> detail = new LinkedList<>();
private Table tblrecord,tblsearchrecord;

public Phonebook(String title){
super(title);
setLayout(new GridLayout(1,1));
setBounds(300,200,700,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
initialize();
// pack();
}

public void initialize(){
tabbedpane = new JTabbedPane();
pnladdrecord = new JPanel();
AddPanel();
tabbedpane.addTab("Add Record",pnladdrecord);
pnlsearch = new JPanel();
searchPanel();
tabbedpane.addTab("Search Record",pnlsearch);
add(tabbedpane);
}

public void AddPanel(){

pnladdrecord.setLayout(new BorderLayout());
JPanel pnladd = new JPanel();

pnladd.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

//First row
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.gridx = 0;
lblname = new JLabel("Name :");
pnladd.add(lblname,c);

c.gridx++;
txtname = new JTextField("",10);
txtname.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent ke){
char c = ke.getKeyChar();
if(!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c == ' '))
ke.consume();
}
});
pnladd.add(txtname,c);

//Second row
c.gridy++;
c.gridx = 0;
lblcontact = new JLabel("Contact No:");
pnladd.add(lblcontact ,c);

c.gridx++;
c.gridwidth = 2;
txtcontact = new JTextField("",10);
txtcontact.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent ke){
char c = ke.getKeyChar();
if(txtcontact.getCaretPosition() == 0){
if((txtcontact.getText().indexOf('+') == -1)){
if(!(Character.isDigit(c)) && !(c == ',') && !(c == '+') )
ke.consume();
}
else{
ke.consume();
}
}
else{
int comma = txtcontact.getText().indexOf(',');
if((txtcontact.getCaretPosition() == (comma+1))){
if(!(Character.isDigit(c)) && !(c == ',') && !(c == '+') )
ke.consume();
}
else{
if(!(Character.isDigit(c)) && !(c == ','))
ke.consume();
}

}

}
});
pnladd.add(txtcontact,c);

//Third row
c.gridy++;
c.gridwidth = 1;
c.gridx = 0;
lblemail = new JLabel("Email Address :");
pnladd.add(lblemail ,c);

c.gridx++;
c.gridwidth = 2;
txtemail = new JTextField("",10);
txtemail.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent ke){
char c = ke.getKeyChar();
int at = txtemail.getText().indexOf('@');
int dot = txtemail.getText().indexOf('.');

if(txtemail.getCaretPosition() == 0){
if((c == '@') || (c == '.'))
ke.consume();
}
else{
if(at == -1){
if((c == '.'))
ke.consume();
}
else if(at != -1 && dot == -1 && txtemail.getCaretPosition() > (at+1)){
if((c == '@'))
ke.consume();
}
else if(at != -1 && dot == -1 && txtemail.getCaretPosition() == (at+1)){
if((c == '@')|| (c == '.'))
ke.consume();
}
else if(at != -1 && dot != -1){
if((c == '@') || (c == '.'))
ke.consume();
}

}

}
});
pnladd.add(txtemail,c);

//Fourth row
c.gridy++;
c.gridwidth = 1;
c.gridx = 0;
lbladdress = new JLabel("Address :");
pnladd.add(lbladdress ,c);

c.gridx++;
c.gridwidth = 2;
txtaddress = new JTextField("",10);
pnladd.add(txtaddress,c);

//Fifth row
c.gridy++;
c.gridwidth = 3;
c.gridx = 0;
lblstatus = new JLabel(" ");
lblstatus.setForeground(Color.RED);
pnladd.add(lblstatus ,c);

//Last row
c.gridy++;
btnadd = new JButton("Add record");
btnadd.addActionListener(this);
pnladd.add(btnadd , c);

pnladdrecord.add(pnladd,BorderLayout.WEST);

tblrecord = new Table();
tblrecord.tableData(pnladdrecord);
}

public void searchPanel(){
pnlsearch.setLayout(new BorderLayout());

JPanel pnl = new JPanel();
pnl.setLayout(new GridLayout(1,3));
lblname = new JLabel("Name :");
pnl.add(lblname);
txtnamesearch = new JTextField("",10);
pnl.add(txtnamesearch);
btnsearch = new JButton("Search");
btnsearch.addActionListener(this);
pnl.add(btnsearch);
pnlsearch.add(pnl,BorderLayout.NORTH);

tblsearchrecord = new Table();
tblsearchrecord.tableData(pnlsearch);

JPanel pnlDelete = new JPanel();
pnlDelete.setLayout(new BorderLayout());
btndelete = new JButton("Delete");
btndelete.addActionListener(this);
btnSave = new JButton("Save");
btnSave.addActionListener(this);
pnlDelete.add(btnSave,BorderLayout.WEST);
pnlDelete.add(btndelete,BorderLayout.EAST);
pnlsearch.add(pnlDelete,BorderLayout.SOUTH);

}

public void actionPerformed(ActionEvent a){
String command = a.getActionCommand();
switch(command){

case "Add record":
Details temp = new Details();
boolean nameverify = true;
for(int i = 0; i< detail.size() ; i++){
temp = detail.get(i);
if((temp.getName().equalsIgnoreCase(txtname.getText().trim()))){
nameverify = false;
}
}

boolean namecheck = !(txtname.getText().trim().equals("")) && nameverify ;
boolean emailcheck = (!(txtemail.getText().indexOf('@') == -1) && !(txtemail.getText().indexOf('.') == -1)) || (txtemail.getText().equals(""));
boolean contactcheck = !(txtcontact.getText().trim().equals(""));
boolean addresscheck = !(txtaddress.getText().trim().equals(""));

if( namecheck && contactcheck && emailcheck && addresscheck  ){

//Adding Details
String tempName = txtname.getText().trim();
String tempContact = txtcontact.getText().trim();
String tempEmail = txtemail.getText().trim();
String tempAddress = txtaddress.getText().trim();
temp = new Details(tempName, tempContact , tempEmail , tempAddress);
detail.add(new Details(tempName, tempContact , tempEmail , tempAddress));

//Adding the record to the table
tblrecord.addRecordToTable(temp);
lblstatus.setText(" Successful");

}
else{
// lblverification.setText(" Invalid Name");
String error;
error = "Unsuccessful!! ";
lblstatus.setText(error);
if(!namecheck){
if(!nameverify)
lblstatus.setText(error + "Name Already Exists");
else
lblstatus.setText(error + " Invalid Name");
}
else if(!contactcheck)
lblstatus.setText(error + " Enter Contact ");
else if(!addresscheck)
lblstatus.setText(error + " Enter Address ");
else if(!emailcheck)
lblstatus.setText(error + " Invalid email ");
}

break;


case "Search":
search();
break;


case "Delete":

int confirm = JOptionPane.showConfirmDialog(new JFrame(),"Are you sure you want to delete these records?",
                            "Confim Message",JOptionPane.YES_NO_OPTION);
                         
                if (confirm == JOptionPane.YES_OPTION) {
               
int[] row = tblsearchrecord.getTable().getSelectedRows();
Object[] name = new String[row.length];
for(int i = 0 ; i < row.length ; i++){
int index = row[i];
name[i] = tblsearchrecord.getDm().getValueAt(index,1);

}

for(int i = 0 ; i < name.length ; i++){
Details temp1;
Object name1 = name[i];

for(int j = 0; j< detail.size() ; j++){
temp1 = detail.get(j);

if((temp1.getName().equals(name1))){
detail.remove(temp1);
tblrecord.getDm().removeRow(j);
search();
}


}

System.out.println ("Details" + detail);
}

tblrecord.getDm().setRowCount(0);
for(int j = 0; j< detail.size() ; j++){
Details temp1 = detail.get(j);
tblrecord.addRecordToTable(temp1);
}
                }
break;

case "Save":

Details temp1;
for(int i = 0 ; i < tblsearchrecord.getDm().getRowCount(); i++){
for(int j = 0; j< detail.size() ; j++){
temp1 = detail.get(j);

if((temp1.getName().equals(tblsearchrecord.getDm().getValueAt(i,1)))){
detail.remove(j);
temp1.putContact(tblsearchrecord.getDm().getValueAt(i,2).toString());
temp1.putEmail(tblsearchrecord.getDm().getValueAt(i,3).toString());
temp1.putAddress(tblsearchrecord.getDm().getValueAt(i,4).toString());
detail.add(j,temp1);
}

}
}


tblrecord.getDm().setRowCount(0);
for(int j = 0; j< detail.size() ; j++){
temp1 = detail.get(j);
tblrecord.addRecordToTable(temp1);
}
search();
break;
}
}

public void search(){
tblsearchrecord.getDm().setRowCount(0);

String namesearch = txtnamesearch.getText();
Details temp;
for( int i = 0; i < detail.size() ; i++){
temp = detail.get(i);

if(temp.getName().toLowerCase().contains(namesearch.toLowerCase())){
int row = tblsearchrecord.getDm().getRowCount();
String[] rowdata = {""+ (row+1) , temp.getName() , temp.getContact() , temp.getEmail() , temp.getAddress() };
tblsearchrecord.getDm().addRow(rowdata);

}
}
}

public static void main (String[] args) {
new Phonebook("Phonebook");
}
}

Thursday, 26 February 2015

Use of JTable in java using DefaultTableModel

//A program to use table using JTable in java with the help of DefaultTableModel

//Note: Add more values to the table either in the code or by using GUI edit mode






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

class TableDemo extends JFrame{
private DefaultTableModel dm;
private JTable table;

public TableDemo(String title){
super(title);
setLayout(new GridLayout(1,1));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
initialize();
pack();
}

public void initialize(){
String[] column_name = {"S.No.","Name","Country","State"};
dm = new DefaultTableModel(column_name,10);
table = new JTable(dm);
JScrollPane scroll = new JScrollPane(table);
add(scroll);

//Sorts the table according the column clicked by the user
table.setAutoCreateRowSorter(true);

String[] record = {"1" , "Mohit" , "India" , "Rajasthan"};
dm.insertRow(0,record);
}

public static void main (String[] args) {
new TableDemo("Table Demo");
}


}

Friday, 13 February 2015

Tambola Game using java

//Below is a program for Tambola game which chooses a random number between 1 to 90 only once. I tried using many other techniques but by far this suited the best to me (Suggestions are entertained).







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

class Tambola extends JFrame implements ActionListener{
private JPanel pnlBoard, pnlButton;
private JButton btnNext, btnReset;
private JLabel lbl[] = new JLabel[90];
private JLabel lblNumber;
private int[] random_number = new int[90];
private int pos = 0;

public Tambola(String title){
super(title);
setVisible(true);
setSize(500,500);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addElements();
pack();
}

public void addElements(){

lblNumber = new JLabel("Tambola Game");
lblNumber.setHorizontalAlignment(0);
lblNumber.setFont(new Font("Cambria",Font.BOLD,28));
lblNumber.setForeground(Color.BLUE);
add(lblNumber,BorderLayout.NORTH);

pnlBoard = new JPanel();
pnlBoard.setLayout(new GridLayout(10,10));
add(pnlBoard,BorderLayout.CENTER);

for(int i = 0 ; i < random_number.length ; i++){
lbl[i] = new JLabel(""+(i+1));
lbl[i].setHorizontalAlignment(0);
pnlBoard.add(lbl[i]);
lbl[i].setOpaque(true);
lbl[i].setBackground(Color.WHITE);
random_number[i] = i;
}

Random rnd = new Random();
   for (int i = random_number.length - 1 ; i > 0 ; i--){
       int index = rnd.nextInt(i + 1);
       int a = random_number[index];
       random_number[index] = random_number[i];
       random_number[i] = a;
   }
   
   pnlButton = new JPanel();
   add(pnlButton,BorderLayout.SOUTH);
   pnlButton.setLayout(new GridLayout(2,2));
 
btnNext = new JButton("Next");
pnlButton.add(btnNext);
btnNext.addActionListener(this);

btnReset = new JButton("Reset");
btnReset.addActionListener(this);
pnlButton.add(btnReset);

lblNumber = new JLabel("Chossed Number: " +random_number[pos]);
pnlButton.add(lblNumber);
}

public void actionPerformed(ActionEvent e){
String command = e.getActionCommand();

if(command == "Next"){
lbl[random_number[pos]].setBackground(Color.BLACK);
lbl[random_number[pos]].setForeground(Color.WHITE);
lblNumber.setText("Chossed Number: " +(random_number[pos]+1));
pos++;
System.out.println (random_number[pos]);
}

else{
pos = 0;
for(int i = 0; i < lbl.length ; i++){
lbl[i].setBackground(Color.WHITE);
lbl[i].setForeground(Color.BLACK);
}
}
}

public static void main (String[] args) {
new Tambola("Tambola");
}
}

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");
}
}

Creating Transparent JPanel using Java

//A program to make the panels transparent in order to view the background unhindered.






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

class PanelTransparensy extends JFrame{
private JPanel pnl1,pnl2,pnl3;

public PanelTransparensy(String title){
super(title);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,250);

// Change the Background color and see the difference yourselves.
getContentPane().setBackground(Color.white);
setVisible(true);
components();
}
public void components(){

// Panel which is more opaque
pnl1 = new JPanel();
pnl1.setBackground(new Color(0,0,0,125));
pnl1.setPreferredSize(new Dimension(250,150));
pnl1.setBorder(BorderFactory.createTitledBorder("First Panel"));
add(pnl1);

// Panel which is translucent
pnl2 = new JPanel();
pnl2.setBackground(new Color(0,0,0,72));
pnl2.setPreferredSize(new Dimension(250,150));
pnl2.setBorder(BorderFactory.createTitledBorder("Second Panel"));
add(pnl2);

// Panel which is Transparent
pnl3 = new JPanel();
pnl3.setBackground(new Color(0,0,0,2));
pnl3.setPreferredSize(new Dimension(250,150));
pnl3.setBorder(BorderFactory.createTitledBorder("Third Panel"));
add(pnl3);
}

public static void main (String[] args) {
new PanelTransparensy("Transaprent");
}
}

Sunday, 1 February 2015

Generic Doubly queue (DeQueue) using Array

/*
This is an example of generic programming for double queue where an element of any datatype can be inserted either from front or back but can be deleted only from front.
*/





import java.util.*;

class Dqueue<E>{
private Object[] lst ;
private int rear = -1 ;
private int front = 0 ;
private int size = 10;

public Dqueue(int size){
this.size = size;
lst = new Object[size];
}

public boolean isFull(){
if((rear == (size - 1)))
return true;
else return false;
}

public boolean isEmpty(){
if(rear == -1)
return true;
else return false;
}

public void insertFront(E ele){
if(!isFull()){
for(int i = rear ; i >= front ; i--){
lst[i+1] = lst[i];
}
lst[front] = ele;
rear++;
System.out.println ("Element Added from  Front :" + ele + " at Pos :" + front);
}
else{
System.out.println ("Overflow");
}
}

public void insertRear(E ele){
if(!isFull()){
rear++;
lst[rear] = ele;
System.out.println ("Element Added from Rear :" + ele + " at Pos :" + rear);
}
else{
System.out.println ("OverFlow");
}

}

public void delete(){
if(!isEmpty()){
System.out.println ("Element Deleted :" + lst[front] + "pos :" + front);
for(int i = front ; i < rear ; i++){
lst[i] = lst[i+1];
}
rear--;

}
else{
System.out.println ("UnderFlow");
}
}

public void printQueue(){
for(int i = front ; i <= rear ; i++){
System.out.println ("Element at pos[" + i + "] is :" + lst[i]);
// System.out.print (lst[i] + "\n");
}
System.out.println ();
}

public void peekFront(){
System.out.println ("Element at first position is :" + lst[front]);
System.out.println ();
}

public void peekRear(){
System.out.println ("Element at last position is :" + lst[rear]);
System.out.println ();
}

public static void main (String[] args) {
System.out.println ("Enter the size of the queue");
int a = (new Scanner(System.in)).nextInt() ;

//Integer

Dqueue<Integer> dq = new Dqueue<Integer>(a);
System.out.println ("Integer Deque");
dq.insertRear(1);
dq.insertRear(2);
dq.delete();
dq.delete();
dq.delete();
dq.insertRear(1);
dq.insertRear(1);
dq.insertFront(5);
dq.printQueue();

//Double
Dqueue<Double> fdq = new Dqueue<Double>(a);
System.out.println ("Double Deque");
fdq.insertFront(1.0);
fdq.insertFront(2.0);
fdq.delete();
fdq.insertRear(7.0);
fdq.insertFront(8.0);
fdq.delete();
fdq.printQueue();


//String
Dqueue<String> sdq = new Dqueue<String>(a);
System.out.println ("String Deque");
sdq.insertFront("Hello");
sdq.insertFront("Friends");
sdq.delete();
sdq.delete();
sdq.insertRear("!!!");
sdq.printQueue();
sdq.peekFront();
sdq.peekRear();

}
}