Saturday, 11 May 2013

Java application for simple calculator using swings


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

public class Calculator extends JFrame implements ActionListener,Runnable
{
  JButton bnum[];
  JButton bback,bce,bc;
  JButton bop[],jdb;
  JLabel jl;
  JTextField tf;
  JPanel p1,p2,p3;
  JDialog jd;
  double d1,d2,d3;
  //long n1,n2,n3;
  boolean frac=false;
  char op;
  boolean opc=false,ope=false;
  public void run()
  {
    while(true)
    {
      char ch=getTitle().charAt(0);
      setTitle(getTitle().substring(1,getTitle().length())+Character.toString(ch));
      try{
       Thread.sleep(200);
      }catch(InterruptedException ie){
       System.out.println(ie);
      }
    }
  }
  public Calculator(String str)
  {
    super(str);
    bnum=new JButton[10];
    jd=new JDialog(this,"Message",true);
    jdb=new JButton("OK");
    jl=new JLabel();
    jd.setLayout(new FlowLayout());
    jdb.setMargin(new Insets(2,5,2,5));
    jd.add(jl); jd.add(jdb);
    jdb.addActionListener(this);
    for(int i=0;i<10;i++)
      bnum[i]=new JButton(Integer.toString(i));
    bback=new JButton("Back");
    bce=new JButton("CE");
    bc=new JButton("C");
    p2=new JPanel();
    p2.setLayout(new FlowLayout());
    p2.add(bback);
    p2.add(bce);
    p2.add(bc);
    tf=new JTextField(15);
    p1=new JPanel();
    p1.add(tf);
    tf.setEditable(false);
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.setText("0.");
    tf.setBackground(Color.white);
    tf.setFont(new Font("Dialog",Font.BOLD,12));
    //System.out.println(tf.getFont());
    bop=new JButton[10];
    bop[0]=new JButton("+");
    bop[1]=new JButton("-");
    bop[2]=new JButton("*");
    bop[3]=new JButton("/");
    bop[4]=new JButton(".");
    bop[5]=new JButton("=");
    bop[6]=new JButton("%");
    bop[7]=new JButton("Sqrt");
    bop[8]=new JButton("1/x");
    bop[9]=new JButton("+/-");
    for(int i=0;i<10;i++){
      bop[i].setMargin(new Insets(2,2,2,2));
      bop[i].addActionListener(this);
    }
    p3=new JPanel();
    p3.setLayout(new GridLayout(4,5,5,5));
    p3.add(bnum[1]);
    p3.add(bnum[2]);
    p3.add(bnum[3]);
    p3.add(bop[0]);
    p3.add(bop[7]);
    p3.add(bnum[4]);
    p3.add(bnum[5]);
    p3.add(bnum[6]);
    p3.add(bop[1]);
    p3.add(bop[8]);
    p3.add(bnum[7]);
    p3.add(bnum[8]);
    p3.add(bnum[9]);
    p3.add(bop[2]);
    p3.add(bop[6]);
    p3.add(bnum[0]);
    p3.add(bop[9]);
    p3.add(bop[4]);
    p3.add(bop[3]);
    p3.add(bop[5]);
    Container c=getContentPane();
    c.setLayout(new FlowLayout());
    c.add(p1);
    c.add(p2);
    c.add(p3);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);
    for(int i=0;i<=6;i++)
      bop[i].setFont(new Font("Dialog",Font.BOLD,13));
    for(int i=0;i<10;i++){
      bnum[i].addActionListener(this);
      bnum[i].setMargin(new Insets(2,10,2,10));
    }
    bce.addActionListener(this);
    bc.addActionListener(this);
    bback.addActionListener(this);
  }
  public void actionPerformed(ActionEvent ae)
  {
    String s=tf.getText();
    String str;
    if(!frac)
      str=s.substring(0,s.length()-1);
    else
      str=s;
    if(ae.getSource()==bback)
    {
      if(frac){
       if(str.charAt(str.length()-1)=='.')
        frac=false;
       else tf.setText(str.substring(0,str.length()-1));
      }
      else{
      if(!str.equals("0"))
       tf.setText(str.substring(0,str.length()-1)+".");
      }
      if(tf.getText().equals("."))
       tf.setText("0.");
    }
    else if(ae.getSource()==bce)
    {
      tf.setText("0.");
      frac=false;
      opc=false;
    }
    else if(ae.getSource()==bc)
    {
      tf.setText("0.");
      d1=0;
      d2=0;
      frac=false;
      opc=false;
      ope=false;
    }
    else if(ae.getSource()==bop[0])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='+';
    }
    else if(ae.getSource()==bop[1])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='-';
    }
    else if(ae.getSource()==bop[2])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='*';
    }
    else if(ae.getSource()==bop[3])
    {
      if(ope){
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       ope=false;
       str=dn;
      }
      d1=Double.parseDouble(str);
      opc=true;
      op='/';
    }
    else if(ae.getSource()==bop[4])
    {
      frac=true;
    }
    else if(ae.getSource()==bop[5])
    {
      if(ope)
      {
       d2=Double.parseDouble(str);
       d3=calc(d1,d2,op);
       String dn=Double.toString(d3);
       if(dn.charAt(dn.length()-1)=='0')
        dn=dn.substring(0,dn.length()-1);
       tf.setText(dn);
       d1=d3;
       opc=false;
       ope=false;
      }
    }
    else if(ae.getSource()==bop[6])
    {
      if(ope)
      {
       double temp=Double.parseDouble(tf.getText());
       String tmp=Double.toString(d1*temp/100);
       if(tmp.charAt(tmp.length()-1)=='0')
        tmp=tmp.substring(0,tmp.length()-1);
       tf.setText(tmp);
      }
      else
       tf.setText("0.");
    }
    else if(ae.getSource()==bop[7])
    {
      double temp=Double.parseDouble(tf.getText());
      String tmp=Double.toString(Math.sqrt(temp));
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
    }
    else if(ae.getSource()==bop[8])
    {
      double temp=Double.parseDouble(tf.getText());
      String tmp=Double.toString(1/temp);
      if(tmp.equals("Infinity")){
       jl.setText("Cannot divided by zero");
       jd.setSize(150,90);
       jd.setResizable(false);
       jd.setVisible(true);
      }
      else{
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
      }
    }
    else if(ae.getSource()==bop[9])
    {
      double temp=Double.parseDouble(tf.getText());
      if(temp!=0){
      String tmp=Double.toString(-1*temp);
      if(tmp.charAt(tmp.length()-1)=='0')
       tmp=tmp.substring(0,tmp.length()-1);
      tf.setText(tmp);
      }else tf.setText("0.");
    }
    else if(ae.getSource()==jdb)
    {
      jd.setVisible(false);
    }
    else
    {
      if(opc){
       tf.setText("0.");
       frac=false;
       str="0";
       ope=true;
       opc=false;
      }
      if(frac)
       tf.setText(str+ae.getActionCommand());
      else{
      if(str.equals("0")){
       tf.setText("");
       tf.setText(ae.getActionCommand()+".");
      }
      else
       tf.setText(str+ae.getActionCommand()+".");
      }
    }
  }
  public double calc(double a,double b,char ch)
  {
    double c=0;
    switch(ch)
    {
      case '+':
       c=a+b;
       break;
      case '-':
       c=a-b;
       break;
      case '*':
       c=a*b;
       break;
      case '/':
       c=a/b;
       break;
    }
    return c;
  }
  public static void main(String[] args) 
  {
    Calculator c=new Calculator("Calculator      ");
    c.setSize(210,250);
    c.setVisible(true);
    Thread t=new Thread(c);
    t.start();
  }
}

Java application for tic tac toe using swings


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

public class TicTacToe implements ActionListener
{
//Instance Variables
private int[][] winCombinations = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
{0, 4, 8}, {2, 4, 6} //diagonal wins
};
private JFrame window = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private int count = 0;
private String letter = "";
private boolean win = false;
private static int startCount =0;
JMenuBar menu = new JMenuBar();
JMenuItem newGame = new JMenuItem("New Game"),
instr = new JMenuItem("Instructions"),
exit = new JMenuItem("Exit"),
name = new JMenuItem("Change Name");
static String x = "X";
static String y = "Y";

public TicTacToe()
{
//Create Window
window.setSize(370,370);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));

//Add Buttons To The Window
for(int i=0; i<=8; i++)
{
buttons[i] = new JButton();
window.add(buttons[i]);
buttons[i].addActionListener(this);
}

menu.add(newGame);
menu.add(name);
menu.add(instr);
menu.add(exit);

name.addActionListener(this);
newGame.addActionListener(this);
exit.addActionListener(this);
instr.addActionListener(this);
window.setJMenuBar(menu);
//Make The Window Visible
window.setVisible(true);
}

public void setName()
{
x = JOptionPane.showInputDialog(null, "Enter Name of player X: ", "", 1);
y = JOptionPane.showInputDialog(null, "Enter Name of player O: ", "", 1);
if(x==null)
{
x = "X";
}
if(y==null)
{
y = "O";
}
if(x.length()==0)
{
x = "X";
}
if(y.length()==0)
{
y = "O";
}
JOptionPane.showMessageDialog(null, "Your names have been set\nTo change your names click on the Change name button in the menu bar","Name Changed!!!",JOptionPane.INFORMATION_MESSAGE);
}

/**
When an object is clicked, perform an action.
@param a action event object
*/
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
//System.out.println(str1+"\t"+str2);

if(source == newGame)
{
int answer = JOptionPane.showConfirmDialog(null, "Your current game will not be saved...\nContinue Anyways??", "Do you want to start a new game?", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}

}
else if(source == name)
{
this.setName();

}
else if(source == instr)
{
JOptionPane.showMessageDialog(null, "Your goal is to be the first player to get 3 X's or O's in a row. (horizontally, diagonally, or vertically)","Instructions",JOptionPane.INFORMATION_MESSAGE);
}
else if(source == exit)
{
int answer = JOptionPane.showConfirmDialog(null, "EXIT", "Are You sure you want to exit??", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}
}
else
{
count++;

/*Calculate whose turn it is*/
if(count % 2 == 0)
{
letter = "O";
}
else
{
letter = "X";
}

/*Write the letter to the button and deactivate it*/
JButton pressedButton = (JButton)source;
pressedButton.setText(letter);
pressedButton.setEnabled(false);

/*Determine who won*/
for(int i=0; i<=7; i++)
{
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
buttons[winCombinations[i][0]].getText() != "")
{
win = true;
}
}

/*Show a dialog when game is over*/
if(win == true)
{
if(letter.equals("X"))
letter = x;
else
letter = y;
JOptionPane.showMessageDialog(null, letter + " wins the game!");
int answer = JOptionPane.showConfirmDialog(null, "Start", "Do you want to start a new game", JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}
else
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}

}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "The game was tie!");
int answer = JOptionPane.showConfirmDialog(null, "Start", "Do you want to start a new game", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
{
this.clearIt();
}
else
{
JOptionPane.showMessageDialog(null, "Thank you " + x+ " and " + y + " for playing");
System.exit(0);
}

}
}
}

public void clearIt()
{

window.setVisible(false);
//this.window = null;
this.startIt();
}

public void startIt()
{
new TicTacToe();

}

public static void main(String[] args)
{

TicTacToe starter = new TicTacToe();
starter.setName();
}
}









Java application for calendar using Swings


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class CalendarDemo extends JFrame implements ItemListener
{
    JPanel p1, p2;
    JComboBox month;
    JComboBox year;
    int days[]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    String months[] = {"January", "February", "March", "April", "May", "June", "July",     "August", "September", "October", "November", "December"};
    public CalendarDemo(String title)
    {
        super();
        setTitle(title);
        p1 = new JPanel();
        //p1.setSize(350, 30);
        //p1.setLayout(new FlowLayout());
        month = new JComboBox();
        for(int i=0;i< months.length;i++)
        {
            month.addItem(months[i]);
        }
        month.addItemListener(this);
        year = new JComboBox();
        for(int i=1980;i<=2099;i++)
        {
            year.addItem(i);
        }
        year.addItemListener(this);
        p1.add(month);
        p1.add(year);
        p2 = new JPanel();
        p2.setLayout(new GridLayout(0,7,5,5));
        Date date = new Date();
        drawCalendar(months[date.getMonth()], (1900+date.getYear()));
        year.setSelectedItem((1900+date.getYear()));
        month.setSelectedItem(months[date.getMonth()]);
        Container c=getContentPane();
        c.setLayout(new FlowLayout());
        add(p1);
        add(p2);
        setVisible(true);
        //setBounds(200, 200, 350, 300);
        setSize(230,220);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String args[])
    {
        CalendarDemo frame = new CalendarDemo("Calendar");
    }

    @Override
    public void itemStateChanged(ItemEvent e)
    {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            drawCalendar((String)month.getSelectedItem(),  (Integer)year.getSelectedItem());
        }
    }
    
    public void drawCalendar(String inputMonth, int inputYear)
    {
        p2.removeAll();
        for(int i=0;i< weekdays.length;i++)
        {
            JLabel label = new JLabel(weekdays[i]);
            label.setHorizontalAlignment(SwingConstants.RIGHT);
            p2.add(label);
        }
        Date date = new Date("01-"+inputMonth+"-"+inputYear);
        int noOfDaysInMonth = days[date.getMonth()];
        if(date.getYear()%4==0 && date.getMonth()==1)
        {
            noOfDaysInMonth = 29;
        }

        for(int i=1, day=1;day<=noOfDaysInMonth;i++)
        {
            for(int j=0;j<7;j++)
            {
                if(day==1)
                {
                    if(j==date.getDay())
                    {
                        JLabel label = new JLabel(String.valueOf(day));
                        label.setHorizontalAlignment(SwingConstants.RIGHT);
                        p2.add(label);
                        day++;
                    }
                    else
                    {
                        JLabel label = new JLabel("");
                        p2.add(label);
                    }
                }
                else
                {
                    JLabel label = new JLabel(String.valueOf(day));
                    label.setHorizontalAlignment(SwingConstants.RIGHT);
                    p2.add(label);
                    day++;
                }
                if(day>noOfDaysInMonth)
                {
                    break;
                }
            }
        }
        p2.validate();
        setTitle(inputMonth+", "+inputYear);
    }
}