Wednesday, 12 February 2014

Paint Utility Application in Java

Wow It was fantastic experience to develop a paint Utility Application in Java:

Following is the program:

package com.mvc;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class Exercise29_3 extends JApplet{

    private ImageIcon lineImageIcon = new ImageIcon("C:\\Users\\TARA BAHADUR THAPA\\Desktop\\line.gif");
    private ImageIcon rectangleImageIcon = new ImageIcon("C:\\Users\\TARA BAHADUR THAPA\\Desktop\\rectangle.gif");
    private ImageIcon ovalImageIcon = new ImageIcon("C:\\Users\\TARA BAHADUR THAPA\\Desktop\\oval.gif");
    private JToolBar jToolBar = new JToolBar();
    private JButton jbtLine = new JButton(lineImageIcon);
    private JButton jbtRectangle = new JButton(rectangleImageIcon);
    private JButton jbtOval = new JButton(ovalImageIcon);
    private DrawPanel drawPanel = new DrawPanel();

    public Exercise29_3(){
        jToolBar.setOrientation(JToolBar.HORIZONTAL);
        jToolBar.setFloatable(true);
        jToolBar.add(jbtLine);
        jToolBar.add(jbtRectangle);
        jToolBar.add(jbtOval);
        add(jToolBar,BorderLayout.NORTH);
        add(drawPanel,BorderLayout.CENTER);
       
        jbtLine.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                drawPanel.setButtonPressed("LINE BUTTON");
            }
        });
       
       
        jbtRectangle.addActionListener(new ActionListener() {
           
            @Override
            public void actionPerformed(ActionEvent e) {
                drawPanel.setButtonPressed("RECTANGLE BUTTON");
            }
        });
       
        jbtOval.addActionListener(new ActionListener() {
           
            @Override
            public void actionPerformed(ActionEvent e) {
                drawPanel.setButtonPressed("OVAL BUTTON");
            }
        });
    }
}

class DrawPanel extends JPanel{
    private int xCoordinate = 0;
    private int yCoordinate = 0;
    private int x = 0;
    private int y = 0;
    private String buttonPressed = "";
   
    public DrawPanel(){
        addMouseListener(new MouseAdapter() {

            public void mousePressed(MouseEvent e){
                xCoordinate = e.getX();
                yCoordinate = e.getY();
            }

        });

        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e){
                System.out.println("Mouse Dragged");
                x = e.getX();
                y = e.getY();
                repaint();
            }
        });
    }
   
    public String getButtonPressed() {
        return buttonPressed;
    }
   
    public void setButtonPressed(String buttonPressed) {
        this.buttonPressed = buttonPressed;
    }
   
   
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        if(!(buttonPressed.equals(""))){
            if(buttonPressed.equals("LINE BUTTON")){
                g.drawLine(xCoordinate, yCoordinate, x, y);
            }
            else if(buttonPressed.equals("RECTANGLE BUTTON")){
                g.drawRect(xCoordinate, yCoordinate, x - xCoordinate, y - yCoordinate);
            }
            else if(buttonPressed.equals("OVAL BUTTON")){
                g.drawOval(xCoordinate, yCoordinate, x - xCoordinate, y - yCoordinate);
            }
        }
    }
}

Every one is welcome to suggest me improvements in this program....

Friday, 18 October 2013

RMI(Remote Method Invocation) program on Interest calculator

InterestCalculatorServerInterface.java

import java.rmi.Remote;
import java.rmi.RemoteException;
public interface InterestCalculatorServerInterface extends Remote{
    public Double getInterestAmount(double interestRate,int numberOfYears,double loanAmount) throws RemoteException;
    public Double getTotalAmount(double loanAmount,double interestAmount) throws RemoteException;
}

InterestCalculatorServerInterfaceImpl.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class InterestCalculatorServerInterfaceImpl extends UnicastRemoteObject implements InterestCalculatorServerInterface{
    public InterestCalculatorServerInterfaceImpl() throws RemoteException{
    }
    public Double getInterestAmount(double interestRate,int numberOfYears,double loanAmount) throws RemoteException{
        double interestAmount = (interestRate * numberOfYears * loanAmount)/100;
        return(new Double(interestAmount));
    }
    public Double getTotalAmount(double loanAmount,double interestAmount) throws RemoteException{
        double totalAmount = loanAmount + interestAmount;
        return(new Double(totalAmount));
    }
}

 RegisterWithRMIRegistry.java

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
public class RegisterWithRMIRegistry{
    public static void main(String []args){
        try{
            InterestCalculatorServerInterface obj = new InterestCalculatorServerInterfaceImpl();
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind("InterestCalculatorServerInterfaceImpl",obj);
            System.out.println("Object "+obj+" registered");
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

InterestCalculatorServerInterfaceClient.java

import java.rmi.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class InterestCalculatorServerInterfaceClient extends JApplet{
    InterestCalculatorServerInterface interest;
    private JTextField jtfAnnualInterestRate = new JTextField();
    private JTextField jtfNumberOfYears = new JTextField();
    private JTextField jtfLoanAmount = new JTextField();
    private JTextArea jtaResult = new JTextArea(10,50);
    private JButton jbtSubmit = new JButton("Submit");
    private JScrollPane scroller = new JScrollPane(jtaResult);
    public void init(){
        initializeRMI();
        setLayout(new FlowLayout());
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4,2,10,10));
        panel.add(new JLabel("Annual Interest Rate "));
        panel.add(jtfAnnualInterestRate);
        panel.add(new JLabel("Number Of Years "));
        panel.add(jtfNumberOfYears);
        panel.add(new JLabel("Loan Amount "));
        panel.add(jtfLoanAmount);
        panel.add(jbtSubmit);
        add(panel,BorderLayout.CENTER);
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        add(scroller,BorderLayout.SOUTH);
        jbtSubmit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                try{
                    Double annualInterestRate = Double.parseDouble(jtfAnnualInterestRate.getText().trim());
                    Integer numberOfYears = Integer.parseInt(jtfNumberOfYears.getText().trim());
                    Double loanAmount = Double.parseDouble(jtfLoanAmount.getText().trim());
                    double interestAmount = interest.getInterestAmount(annualInterestRate.doubleValue(),numberOfYears.intValue(),loanAmount.doubleValue());
                    double totalAmount = interest.getTotalAmount(loanAmount,interestAmount);
                    jtaResult.append("Annual Interest Rate :"+annualInterestRate.toString()+"\n");
                    jtaResult.append("Number of Years :"+numberOfYears.toString()+"\n");
                    jtaResult.append("Annual Interest Rate :"+loanAmount.toString()+"\n");
                    jtaResult.append("interest Amount :"+(new Double(interestAmount)).toString()+"\n");
                    jtaResult.append("total Amount :"+new Double(totalAmount)+"\n");
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        });
    }
    protected void initializeRMI(){
            try{
                Registry registry = LocateRegistry.getRegistry("localhost");
                interest = (InterestCalculatorServerInterface)registry.lookup("InterestCalculatorServerInterfaceImpl");
                System.out.println("Server object "+interest+" found");
            }catch(Exception ex){
                System.out.println(ex);
            }
    }
    public static void main(String[]args){
        InterestCalculatorServerInterfaceClient applet = new InterestCalculatorServerInterfaceClient();
        JFrame frame = new JFrame();
        frame.setTitle("InterestCalculatorServerInterfaceClient");
        frame.add(applet,BorderLayout.CENTER);
        frame.setSize(300,300);
        applet.init();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(3);
    }
}

RMI(Remote Method Invocation Program) on Visit Count

VisitCountServerInterface.java

import java.rmi.Remote;
import java.rmi.RemoteException;
public interface VisitCountServerInterface extends Remote{
    public Integer visitCount() throws RemoteException;
}

VisitCountServerInterfaceImpl.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class VisitCountServerInterfaceImpl extends UnicastRemoteObject implements VisitCountServerInterface{
    public static int visitCount = 0;
    public VisitCountServerInterfaceImpl() throws RemoteException{
    }
    public Integer visitCount() throws RemoteException{
        visitCount++;
        return(new Integer(visitCount));
    }
}

RegisterWithRMIServer.java

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RegisterWithRMIServer{
    public static void main(String args[]){
        try{
            VisitCountServerInterface visitCounter = new VisitCountServerInterfaceImpl();
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind("VisitCountServerInterfaceImpl",visitCounter);
            System.out.println("Object "+visitCounter+" registered");
        }catch(Exception ex){
        }
    }
}

VisitCountServerInterfaceClient.java

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class VisitCountServerInterfaceClient extends JApplet{
    VisitCountServerInterface visitCounter;
    int visitCount;
    public void init(){
        initializeRMI();
        add(new JLabel("The Visit Count is :"+(new Integer(visitCount)).toString()));
    }
    public void initializeRMI(){
        try{
            Registry registry = LocateRegistry.getRegistry("localhost");
            visitCounter = (VisitCountServerInterface)registry.lookup("VisitCountServerInterfaceImpl");
            visitCount = visitCounter.visitCount();
        }catch(Exception ex){
        }
    }
    public static void main(String []args){
        VisitCountServerInterfaceClient applet = new VisitCountServerInterfaceClient();
        JFrame frame = new JFrame("VisitCountServerInterfaceClient");
        frame.add(applet,BorderLayout.CENTER);
        frame.setSize(300,300);
        applet.init();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(3);
    }
}

Saturday, 28 September 2013

A small mistake in Liang book

There is a small mistake in liang book. I was going through this heap Data Structure in the book,I found out that parent index , left child index and right child index needs correction
In the book
Parent index = (currentIndex - 1)/2
leftChild Index = (2 * currentIndex);
rightChildIndex = (2 * currentIndex + 1);
this is giving wrong results
Proof:
but in actual it should be:
package com.liang.datastructures;

import java.util.ArrayList;

public class Heap {
    private  ArrayList list = new ArrayList();
    public Heap(){
    }
    public ArrayList getList() {
        return list;
    }
    public void setList(ArrayList list) {
        this.list = list;
    }
    public Heap(Object []objects){
        for(int i=0;i<objects.length;i++){
            add(objects[i]);
        }
    }
    public  void add(Object obj){
        list.add(obj);
        int currentIndex = list.size() - 1;
        int parentIndex;
        while(currentIndex > 0){
            parentIndex = (currentIndex - 1)/2;
            if(((Comparable)(list.get(currentIndex))).compareTo(list.get(parentIndex)) > 0){
                Object temp = list.get(currentIndex);
                list.set(currentIndex,list.get(parentIndex));
                list.set(parentIndex,temp);
            }
            else
            {
                break;
            }
            currentIndex = parentIndex;
        }
    }
    public Object remove(){
        if(list.size() == 0) return null;
        Object removedObject = list.get(0);
        list.set(0,list.get(list.size() - 1));
        list.remove(list.size() - 1);
        int currentIndex = 0;
        while(currentIndex < list.size()){
            int leftChildIndex = 2 * currentIndex;
            int rightChildIndex = 2 * currentIndex + 1;
            if(leftChildIndex >= list.size()){
                break;
            }
            int maxIndex = leftChildIndex;
            if(rightChildIndex < list.size()){
                if(((Comparable)(list.get(leftChildIndex))).compareTo(list.get(rightChildIndex)) < 0){
                    maxIndex = rightChildIndex;
                }
            }
            if(((Comparable)(list.get(currentIndex))).compareTo(list.get(maxIndex))<0){
                Object temp = list.get(currentIndex);
                list.set(currentIndex,list.get(maxIndex));
                list.set(maxIndex,temp);
                currentIndex = maxIndex;
            }
            else{
                break;
            }
        }
        return removedObject;
    }
    public int getSize(){
        return(list.size());
    }
}


package com.liang.datastructures;

public class HeapSort {
    public static void main(String[] args) {
        Heap heap = new Heap(new Integer[]{2,3,1,4,7,9,8,6,5});
        while(heap.getSize() > 0){
            System.out.println(" "+heap.remove());
        }
    }
}

Result:
 9
 6
 8
 5
 7
 4
 3
 2
 1



Parent index = (currentIndex )/2
leftChild Index = (2 * currentIndex + 1);
rightChildIndex = (2 * currentIndex + 2);
this is giving correct results
proof: 

package com.liang.datastructures;

import java.util.ArrayList;

public class Heap {
    private  ArrayList list = new ArrayList();
    public Heap(){
    }
    public ArrayList getList() {
        return list;
    }
    public void setList(ArrayList list) {
        this.list = list;
    }
    public Heap(Object []objects){
        for(int i=0;i<objects.length;i++){
            add(objects[i]);
        }
    }
    public  void add(Object obj){
        list.add(obj);
        int currentIndex = list.size() - 1;
        int parentIndex;
        while(currentIndex > 0){
            parentIndex = currentIndex /2;
            if(((Comparable)(list.get(currentIndex))).compareTo(list.get(parentIndex)) > 0){
                Object temp = list.get(currentIndex);
                list.set(currentIndex,list.get(parentIndex));
                list.set(parentIndex,temp);
            }
            else
            {
                break;
            }
            currentIndex = parentIndex;
        }
    }
    public Object remove(){
        if(list.size() == 0) return null;
        Object removedObject = list.get(0);
        list.set(0,list.get(list.size() - 1));
        list.remove(list.size() - 1);
        int currentIndex = 0;
        while(currentIndex < list.size()){
            int leftChildIndex = 2 * currentIndex + 1;
            int rightChildIndex = 2 * currentIndex + 2;

            if(leftChildIndex >= list.size()){
                break;
            }
            int maxIndex = leftChildIndex;
            if(rightChildIndex < list.size()){
                if(((Comparable)(list.get(leftChildIndex))).compareTo(list.get(rightChildIndex)) < 0){
                    maxIndex = rightChildIndex;
                }
            }
            if(((Comparable)(list.get(currentIndex))).compareTo(list.get(maxIndex))<0){
                Object temp = list.get(currentIndex);
                list.set(currentIndex,list.get(maxIndex));
                list.set(maxIndex,temp);
                currentIndex = maxIndex;
            }
            else{
                break;
            }
        }
        return removedObject;
    }
    public int getSize(){
        return(list.size());
    }
}
package com.liang.datastructures;

public class HeapSort {
    public static void main(String[] args) {
        Heap heap = new Heap(new Integer[]{2,3,1,4,7,9,8,6,5});
        while(heap.getSize() > 0){
            System.out.println(" "+heap.remove());
        }
    }
}


Result:
 9
 8
 7
 6
 5
 4
 3
 2
 1

Sunday, 7 April 2013

Fan Which can be started,stoped and reversed

FanControl.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FanControl extends JPanel{
    private JButton btnStart = new JButton("Start");
    private JButton btnStop = new JButton("Stop");
    private JButton btnReverse = new JButton("Reverse");
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    public Fan fan = new Fan();
    private JScrollBar jscbHort = new JScrollBar(JScrollBar.HORIZONTAL);
    public FanControl(){
        setLayout(new BorderLayout());
        p1.setLayout(new GridLayout(1,3,0,0));
        p1.add(btnStart);
        p1.add(btnStop);
        p1.add(btnReverse);
        p2.setLayout(new GridLayout(1,1,0,0));
        p2.add(jscbHort);
        add(p1,BorderLayout.NORTH);
        add(fan,BorderLayout.CENTER);
        add(p2,BorderLayout.SOUTH);
        btnStart.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                fan.start();
            }
        });
        btnStop.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                fan.stop();
            }
        });
        btnReverse.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                fan.reverse();
            }
        });
        jscbHort.addAdjustmentListener(new AdjustmentListener(){
            public void adjustmentValueChanged(AdjustmentEvent ae){
                double value = jscbHort.getValue();
                double maximumValue = jscbHort.getMaximum();
                int delay = p2.getWidth() - (int)(value * p2.getWidth()/maximumValue);
                delay = delay/10;
                System.out.println(delay);
                fan.setSpeed(delay);
            }
        });
    }
}


FanControlApplet.java

import java.awt.*;
import javax.swing.*;
public class FanControlApplet extends JApplet{
    FanControl fanControl = new FanControl();
    public void init(){
        add(fanControl);
    }
    public static void main(String []args){
        JFrame frame = new JFrame("Fan Control");
        FanControlApplet applet = new FanControlApplet();
        applet.init();
        frame.add(applet);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

An Alarm Clock

AlarmClock.java

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.net.URL;
import java.applet.*;
public class AlarmClock extends JPanel{
    private JLabel jlblHour = new JLabel("Hour");
    private JLabel jlblMinute = new JLabel("Minute");
    private JLabel jlblSecond = new JLabel("Second");
    private JTextField jtfHour = new JTextField();
    private JTextField jtfMinute = new JTextField();
    private JTextField jtfSecond = new JTextField();
    private JPanel p1 = new JPanel();
    private JCheckBox jchk = new JCheckBox("Alarm");
    private JButton btnSetAlarm = new JButton("Set Alarm");
    AudioClip audioClip;
    private JPanel p2 = new JPanel();
    private int hour;
    private int minute;
    private int second;
    SetAlarm frame = new SetAlarm();
    int i = 0;
    private static Calendar gCalendar = new GregorianCalendar();
    public static int alarmHour = 0;
    public static int alarmMinute = 0;
    public static int alarmSecond = 0;
    Timer timer2;
    public AlarmClock(){
        setLayout(new BorderLayout());
        Timer timer1 = new Timer(1000,new TimerListener1());
        timer1.start();
        p1.setLayout(new GridLayout(3,2,5,5));
        p1.add(jlblHour);
        p1.add(jtfHour);
        p1.add(jlblMinute);
        p1.add(jtfMinute);
        p1.add(jlblSecond);
        p1.add(jtfSecond);
        gCalendar = new GregorianCalendar();
        hour = gCalendar.get(Calendar.HOUR);
        minute = gCalendar.get(Calendar.MINUTE);
        second = gCalendar.get(Calendar.SECOND);
        jtfHour.setText("" + hour);
        jtfMinute.setText("" + minute);
        jtfSecond.setText("" + second);
        p1.setBorder(new LineBorder(Color.BLACK,1));
        p2.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
        p2.add(jchk);
        p2.add(btnSetAlarm);
        jchk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                if(jchk.isSelected())
                {
                    timer2 = new Timer(0,new TimerListener2());
                    timer2.start();
                }
            }
        });
        btnSetAlarm.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        add(p1,BorderLayout.CENTER);
        add(p2,BorderLayout.SOUTH);
    }
    public class TimerListener2 implements ActionListener{
        public void actionPerformed(ActionEvent ae){
            if((hour == alarmHour)&&(minute == alarmMinute)&&(second == alarmSecond))
            {
                URL urlForAudio = getClass().getResource("image/Bbpledge.wav");
                audioClip = Applet.newAudioClip(urlForAudio);
                audioClip.loop();
            }
        }
    }
    public void setTime(){
        setCurrentTime();
        jtfHour.setText("" + hour);
        jtfMinute.setText("" + minute);
        jtfSecond.setText("" + second);
    }
    class TimerListener1 implements ActionListener{
        public void actionPerformed(ActionEvent ae){
            setTime();
        }
    }
    public void setCurrentTime(){
        gCalendar = new GregorianCalendar();
        hour = gCalendar.get(Calendar.HOUR);
        minute = gCalendar.get(Calendar.MINUTE);
        second = gCalendar.get(Calendar.SECOND);
    }
    public static void setAlarmTime(int hour,int minute,int second){
        alarmHour = hour;
        alarmMinute = minute;
        alarmSecond = second;
    }
}


AlarmClockFrame.java

import javax.swing.*;
public class AlarmClockFrame extends JFrame{
    public AlarmClockFrame(){
        add(new AlarmClock());
    }
    public static void main(String []args){
        AlarmClockFrame frame = new AlarmClockFrame();
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}