Sunday, January 23, 2011

Treap algorithm java


 Description of the Algorithm


According to the definition of problem set 01, it gives the basic idea of binary search tree insert and then performing relevant rotations to restore the min-heap property. Each insertion to this data structure comprises of a key and a unique priority.

Conditions


ü    if v is a left child of u, then key[v] < key[u]
ü    if v is a right child of u, then key[v] > key[u]
ü    if v is a child of u, then priority(v) > priority(u)

Assumptions


ü    I expect that user will enter all the requests and then try to view the tree.
ü    User will input valid inputs. (I have not validated the user inputs)

Pseudo Code of the Algorithm


Element x
While x != root and priority (x) < priority of parent (x)
BEGIN
if current root == nullNode
 THEN
 root == x;
If key of x < =key of parent   WE CAN CHECK EQUALITY AND LESS THAN IF  WE WANT TO    ACCEPT DUPLICATE KEYS.
Insert into left child.
 If priority of x > priority of parent
BEGIN  RotateWithLeftChild(x);
END IF
END IF
If key of x > key of parent
BEGIN
Insert into left child.
THEN     If priority of x < priority of parent
BEGIN
RotateWithRightChild(x);
END IF
END IF
END WHILE



Running time of the Algorithm


A treap with n nodes is equivalent to a randomly built binary search tree with n nodes. Because that assigning priorities to nodes as they are inserted into the treap is the same as inserting to the binary search tree n nodes in the increasing order defined by their priorities. So if we assign the priorities randomly, we get a random order of n priorities, which is the same as a random permutation of the n inputs, so we can view this as inserting the n items in random order.

TREAP-INSERT first inserts an item in the tree using the normal binary search tree
insert and then performs a number of rotations to restore the min-heap property. The normal binary-search-tree insertion algorithm TREE-INSERT always places the new item at a new leaf of tree. Therefore the time to insert an item into a treap is proportional to the height of a randomly built binary search tree, which as we saw in lecture is O(lg n) in expectation.
The maximum number of rotations occurs when the new item receives a priority less than all priorities in the tree. In this case it needs to be rotated from a leaf to the root. An upper bound on the number of rotations is therefore the height of a randomly built binary search tree, which is O(lg n) in expectation.
Because each rotation take constant time, the expected time to rotate is O(lg n).




Sources


/* Roshan Fernando
 * Orginal Author Mark Weiss
 * 2011-01-15
 */
package ProblemSet01;

// Basic node stored in treaps
import java.util.Random;

/** Note that this class is not accessible outside
  * of package ProblemSet01
 */
class TreapNode {

private static Random randomObj = new Random();
    // Constructors

    TreapNode(Comparable theElement) {
        this(theElement, null, null, 0);
    }

    TreapNode(Comparable theElement, TreapNode lt, TreapNode rt, int prior) {
        element = theElement;
        left = lt;
        right = rt;
        priority = prior;//randomObj.nextInt();
    }

    /**
     * can use this Overload for the
     * Auto generated Priorites
     * @param theElement
     * @param lt
     * @param rt
     */
    TreapNode(Comparable theElement, TreapNode lt, TreapNode rt) {
        element = theElement;
        left = lt;
        right = rt;
        priority = randomObj.nextInt();
    }
    // Friendly data; accessible by other package routines
    Comparable element;      // The data in the node
    TreapNode left;         // Left child
    TreapNode right;        // Right child
    int priority;     // Priority
   
}


/* Roshan Fernando
 * Orginal Author Mark Weiss
 * 2011-01-15
 */
package ProblemSet01;

import java.util.Random;
import java.util.Stack;// this is for the printing purpose only.
import java.util.Scanner;

public class Treap {

    private TreapNode root;
    private static TreapNode nullNode;

    static // Static initializer for NullNode
    {
        nullNode = new TreapNode(null);
        nullNode.left = nullNode.right = nullNode;
        nullNode.priority = Integer.MAX_VALUE;
    }

    public Treap() {
        root = nullNode;
    }

    /**
     * Insert into the tree.
     * @param x the item to insert.
     * @param  pr the priority
     */
    public void insert(Comparable x, int pr) {
        root = insert(x, root, pr);
    }

    /**
     * Test if the tree is logically empty.
     * @return true if empty, false otherwise.
     */
    public boolean isEmpty() {
        return root == nullNode;
    }

    /**
     * Print the tree contents in sorted order.
     */
    public void printTree() {
        if (isEmpty()) {
            System.out.println("Empty tree");
        } else {
            printTree(root);
        }
    }


    /**
     * Internal Overloaded method to insert into a subtree.
     * @param x the item to insert.
     * @param t the node that roots the tree.
     * @param  pr the priority of the new Item.
     * @return the new root.
     */
    private TreapNode insert(Comparable x, TreapNode t, int pr) {
        if (t == nullNode) {
            t = new TreapNode(x, nullNode, nullNode, pr);
        } else if (x.compareTo(t.element) <= 0) {
            t.left = insert(x, t.left, pr);
            if (t.left.priority <= t.priority) {
                t = rotateWithLeftChild(t);
            }
        } else if (x.compareTo(t.element) > 0) {
            t.right = insert(x, t.right, pr);
            if (t.right.priority < t.priority) {
                t = rotateWithRightChild(t);
            }
        }

        return t;
    }

    /**
     * Internal Overloaded method to insert into a subtree.
     * for auto Generated priority.
     * @param x the item to insert.
     * @param t the node that roots the tree.
     * @return the new root.
     */
    private TreapNode insert(Comparable x, TreapNode t) {
        if (t == nullNode) {
            t = new TreapNode(x, nullNode, nullNode);
        } else if (x.compareTo(t.element) <= 0) {
            t.left = insert(x, t.left);
            if (t.left.priority < t.priority) {
                t = rotateWithLeftChild(t);
            }
        } else if (x.compareTo(t.element) > 0) {
            t.right = insert(x, t.right);
            if (t.right.priority < t.priority) {
                t = rotateWithRightChild(t);
            }
        }
        return t;
    }




   
/**
     * Internal method to print a subtree in sorted order.
     * @param t the node that roots the tree.
     */
    private void printTree(TreapNode t) {

        if (t != t.left) {
            printTree(t.left);
            System.out.println(t.element.toString() + "\t[" + t.priority + "]");
            printTree(t.right);
        }
    }

    /**
     * Rotate binary tree node with left child.
     */
    private static TreapNode rotateWithLeftChild(TreapNode k2) {
        TreapNode k1 = k2.left;
        k2.left = k1.right;
        k1.right = k2;
        return k1;
    }

    /**
     * Rotate binary tree node with right child.
     */
    private static TreapNode rotateWithRightChild(TreapNode k1) {
        TreapNode k2 = k1.right;
        k1.right = k2.left;
        k2.left = k1;
        return k2;
    }

    /**
     * Generates a letter,
     * Duplicates are allowed.
     * @return char Alphabet
     */
    private static char letterGenerate() {
        char alphabet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        Random generator = new Random();
        return alphabet[generator.nextInt(25)];
    }








   

/**
     * just to print the treap
     */
    public void displayTree() {
        System.out.println("          ! ... Visual Tree  ... !");
        Stack globalStack = new Stack();
        globalStack.push(root);
        int nBlanks = 32;
        boolean isRowEmpty = false;
        System.out.println("......................................................");

        while (isRowEmpty == false) {
            Stack localStack = new Stack();
            isRowEmpty = true;
            for (int j = 0; j < nBlanks; j++) {
                System.out.print(" ");
            }
            while (globalStack.isEmpty() == false) {
                TreapNode temp = (TreapNode) globalStack.pop();
                if (temp != null && temp.element != null) {
                    System.out.print(temp.element + "[" + temp.priority + "]");
                    localStack.push(temp.left);
                    localStack.push(temp.right);
                    if (temp.left != null || temp.right != null) {
                        isRowEmpty = false;
                    }
                } else {
                    System.out.print("--");
                    localStack.push(null);
                    localStack.push(null);
                }
                for (int j = 0; j < nBlanks * 2 - 2; j++) {
                    System.out.print(" ");
                }
            } // end while globalStack not empty
            System.out.println();
            nBlanks /= 2;
            while (localStack.isEmpty() == false) {
                globalStack.push(localStack.pop());
            }
        } // end while isRowEmpty is false
        System.out.println("......................................................");
    }










    /**
     * for manual input to the tree
     * @param obj
     * @return Treap
     */
    private static Treap manualInput(Treap objTreap) {
        Scanner objRead = new Scanner(System.in);
        boolean isContinue = true;
        try {
            do {
                System.out.println("Please Enter a Literal ");
                char element = objRead.next().trim().charAt(0);
                System.out.println("Please enter a priority (Integer)");
                int pr = objRead.nextInt();
                objTreap.insert(element, pr);
                System.out.println("if you want to continue press 1,\n  press any other key to exit.");
                isContinue = objRead.next().trim().equals("1");
            } while (isContinue);
        } catch (Exception e) {
            System.out.println("Error " + e.getMessage());
        } finally {
            return objTreap;
        }
    }

    /**
     * auto Generated Insert to tree
     * @param objTreap
     * @return objTreap
     */
    private static Treap autoGenerate(Treap objTreap) {
        Scanner objRead = new Scanner(System.in);
        boolean isContinue = true;
        do {
            char c = letterGenerate();
            int pr = new Random().nextInt();

            System.out.println("Generated Alphabel character\t" + c + " priority [" + pr + "]");
            objTreap.insert(c, pr);

            System.out.println("if you want to continue press 1,\n  press any other key to exit.");
            isContinue = objRead.next().trim().equals("1");

        } while (isContinue);

        return objTreap;

    }




   
// Test program
    public static void main(String[] args) {
        Treap objTreap = new Treap();
        // checking the given values with their priorities.
        objTreap.insert('A', 10);
        objTreap.insert('B', 7);
        objTreap.insert('E', 23);
        objTreap.insert('G', 4);
        objTreap.insert('H', 5);
        objTreap.insert('K', 65);
        objTreap.insert('I', 73);
        objTreap.insert('C', 25);
        objTreap.insert('D', 9);
        objTreap.insert('F', 2);     
     

        Scanner objRead = new Scanner(System.in);
        System.out.println("Press 0 for auto Generation, Press 1 for Manual inputs");
        int intOption = objRead.nextInt();
        switch (intOption) {
            case 0:
                objTreap = autoGenerate(objTreap);
                break;
            case 1:
                objTreap = manualInput(objTreap);
                break;
            default:
                System.out.println("Errorneous input");
        }


        System.out.println("! ... in Order Traversal ... !");

        objTreap.printTree();
        objTreap.displayTree();

    }
}

Monday, January 17, 2011

Pass Values using queryString

Hi folks !!!!
Again guys this is also about web pages, do you ever wanted to pass a value from a page to another , this is the most fundamental way of doing it .
 So lets say you have a textBox  accepting name of the user , and you want to set that value to a label  in next page .

this is the simple way....

// hfCode is a hiddenField and txtLogin is my textbox, and Login ,code are my parameters.
Response.Redirect("URladdress.aspx?Login=" +
txtLogin.Text + "&Code=" +
hfCode.Value);

So in the receiving end  or the page all you have to do is ,

if (Request.QueryString["Login"] != null && Request.QueryString["Code"])
{
lblWelcome.Text = "Welcome "+ Request.QueryString["Login"]
+" "+
      Request.QueryString["Code"];
                   }


That's all,
Enjoy.

P.S. make sure to check that parameters are not null before accessing




Tuesday, January 11, 2011

Unload event handler javaScript

Hey Folks !!!


this is simple javaScript to handle the Unload event.
this is the Script for that .. 
And on your HTML page declare like this.

<html>
//call the function here 
<body OnUnload="unloadHandle()">
</html>



<script language="javascript" type="text/javascript">
            function unloadHandle() {
                    try{
                               get the element which decide whether to fire the action.
                                may be hiddenfield.
                            
                                var val = document.getElementById("hfGenerateClick");
                        //ideal would be if the value != "1" then fire ..
                    if(val.value == "1")
                        alert("nice");
                    else
                        confirm("are you sure ?");
                    }
                    catch(err)
                    {alert(err.description);}
                }           
       
</script>

Wednesday, January 5, 2011

send c# Web request (http/https)

Hey folks..!!!
this is something i wanted to do while developing a web application.. i just wanted post some data to verify my site working accordingly.
Hope this one will be helpful.
                WebRequest request = WebRequest.Create("your site address"));
                request.Method = "POST";
       //Cast if it is https simply for the secured connections
               // ((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;
                string postData = "yout data";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();
              // get the response
                dataStream.Close();
                response.Close();
            }

P.S.
remenber to add 


using System.IO;
using System.Net;
 hi folks !!
this is C# about sending ping request.
 
private void HostPing(string host, int timeout)
    {
//host can be an ip 
         Ping pingSender = new Ping();
        PingOptions options = new PingOptions();

        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.

        options.DontFragment = true;

        // Create a buffer of 32 bytes of data to be transmitted.

        string data = "dsfgsdfgsdfgsdfgdsfg ";
        byte[] buffer = Encoding.ASCII.GetBytes(data);

        PingReply reply = pingSender.Send(host, timeout, buffer, options);
 // check  reply.Status  if ya want ...

      //  return (reply.Status == IPStatus.Success);

    }

 //this is to send a request with the port defined
private void checkHostAndPortAvailability(string host, int port)
    {
        IPHostEntry IPHost = new IPHostEntry();
        IPHost = Dns.GetHostEntry(host);

        IPAddress IPAddr = IPHost.AddressList[0];

        try
        {

            TcpClient TcpCli = new TcpClient();
            TcpCli.Connect(IPAddr, port);
            TcpCli.Close();
//if succussful reach here,  else go to catch
        }
        catch (Exception ex)
        {
            // error handling code
        }
    }


N.B.



using System.Net.NetworkInformation;
using System.Net.Sockets; note to add these usings

Tuesday, January 4, 2011

Crystal report Function to format with leading Zeroes..

hey folks .. 

this is something that i have come across while doing some development .
my requirement was to format integer database column with leading zeroes with Crystal Report.

i have a dataset called OrderDetails and i am formatting it to have 10 digits where the leading digits will be filled with zeroes. e.g. 21 will be 0000000021


this is how i did it.
in crystal report you have to write a function . (write click formula field then select new)

ReplicateString ("0",10-Length(cstr ({OrderDetails.Id},0,""))) +cstr({OrderDetails.Id},0,"") 
simple like this
P.S remember save,press x+2 button to validate and add this to your report lol ...!!!!

Monday, January 3, 2011

java Shopping Cart with swing

package OnlineShop;

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


public class Login
{

    protected JFrame jfrmLogin = new JFrame ("Login");
    protected JPasswordField txtPassword = new JPasswordField(10);
    protected JTextField txtLoginName = new JTextField(10);
    protected JPanel jplLogin = new JPanel(null);
    protected JLabel lblMessage = new JLabel("");
    protected JButton btnSubmit = new JButton("Login");
    protected JButton btnCancel = new JButton("Cancel");


    public static void main(String[] args)
    {
        new Login().display();
        JFrame.setDefaultLookAndFeelDecorated(true);
    }

   void display()
   {

       JLabel lblLoginName = new JLabel("Login Name");
       JLabel lblPassword = new JLabel("Password");

       Container contPane = jfrmLogin.getContentPane();

        lblLoginName.setLabelFor(txtLoginName);

        lblPassword.setLabelFor(txtPassword);

        lblLoginName.setBounds(50,50,100,20);
        txtLoginName.setBounds(150,50, 150, 20);
        txtLoginName.setText("admin");
        lblPassword.setBounds(50,80,100,20);
        txtPassword.setBounds(150,80, 150, 20);
        txtPassword.setText("admin123");

        btnSubmit.setBounds(150,120,100,25);

        lblMessage = new JLabel();
        jplLogin.add(lblLoginName);
        jplLogin.add(txtLoginName);
        jplLogin.add(lblPassword);
        jplLogin.add(txtPassword);
        jplLogin.add(btnSubmit);
        jplLogin.add(lblMessage);

        lblMessage.setFont(new Font("Calibri", Font.ITALIC, 15));
        lblMessage.setForeground(Color.darkGray);
        contPane.add(jplLogin);
        contPane.add(lblMessage,BorderLayout.PAGE_START);

     

       txtPassword.setText("admin123");
       txtLoginName.setText("admin");
       btnSubmit.addActionListener(new MyActionListener(this));
       btnCancel.addActionListener(new MyActionListener(this));






        jfrmLogin.getRootPane().setDefaultButton(btnSubmit);
        jfrmLogin.setSize(375,275);
        jfrmLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrmLogin.setVisible(true);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = jfrmLogin.getSize().width;
        int h = jfrmLogin.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

     
        jfrmLogin.setLocation(x, y);

   }
}

class MyActionListener implements ActionListener
{
    Login objLog;
    MyActionListener(Login log)
    {
        this.objLog = log;
    }

    public void actionPerformed(ActionEvent e)
    {
        User objUser = new User();
        objLog.lblMessage.setFont(new Font("Trebuchet Ms", Font.PLAIN, 14));
        objLog.lblMessage.setForeground(Color.BLACK);

        if (e.getSource() == objLog.btnSubmit)
        {
            if(objLog.txtLoginName.getText().isEmpty() || objLog.txtPassword.getText().isEmpty())
            {
                objLog.lblMessage.setText("Login Name / Password required to Login");
                objLog.jplLogin.setBackground(Color.RED);
                objLog.jfrmLogin.repaint();
            }
            else
            {
                if (objLog.txtLoginName.getText().equals(objUser.getLoginName()) && objLog.txtPassword.getText().equals(objUser.getPassword()))
                {
                   objLog.jplLogin.setBackground(Color.GREEN);
                   objLog.jfrmLogin.setVisible(false);
                   new ProductSelection(objUser).display();
                   objLog.jfrmLogin.dispose();
                }
                else
                {
                    objLog.jplLogin.setBackground(Color.RED);
                    objLog.lblMessage.setText("Incorrect login name / password");
                    objLog.jfrmLogin.repaint();
                }
            }
        }

        if (e.getSource() == objLog.btnCancel)
        {
            System.exit(0);
        }
    }



}

image path had hard  coded

package OnlineShop;

/**
 *
 * @author Roshan
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.util.*;

public class ImagePanel
{
    ProductSelection productSel;

    ImagePanel(ProductSelection pro)
    {
        productSel =pro;
    }

    JPanel hpPanel(User authUser)
    {
        JPanel panelLaptopHp = new JPanel();
            panelLaptopHp.add(this.CreateJPanel(new Product(115000, "HP Pavilion DV6 3061", "<html>Core i7 1.6GHz, 6GB DDR3,<br>640GB,1GB VGA,<br>Win7</html>"),"Laptop_HP_1.jpg", authUser));
            panelLaptopHp.add(this.CreateJPanel(new Product(85000, "HP Pavilion dv5t series", "<html>Core i3 2.6GHz, 2GB DDR3,<br>640GB,1GB VGA,<br>Win7</html>"),"Laptop_HP_2.jpg", authUser));
            panelLaptopHp.add(this.CreateJPanel(new Product(105000, "HP Pavilion dv4 series", "<html>Core i5 2.6GHz, 4GB DDR3,<br>500GB,1GB VGA,<br>Win7</html>"),"Laptop_HP_3.jpg", authUser));
            panelLaptopHp.add(this.CreateJPanel(new Product(115000, "HP Pavilion dm3t series", "<html>Core dual core 2.4 GHz,<br> 6GB DDR2,320GB,512MB VGA,<br>Win7</html>"),"Laptop_HP_4.jpg", authUser));
            return panelLaptopHp;
    }

    JPanel dellPanel(User authUser)
    {

        JPanel panelLaptopDell= new JPanel();

            panelLaptopDell.add(this.CreateJPanel(new Product(95000, " dell 620", "<html>Core dual core 2.6GHz,<br> 2GB DDR2,<br>320GB,1GB VGA,<br>DOS </html>"),"Laptop_Dell_1.jpg", authUser));
            return panelLaptopDell;

    }

    JPanel iBMDeskPanel (User authUser){
         JPanel panelIBM = new JPanel();

            panelIBM.add(this.CreateJPanel(new Product(55000, "IBM PC 300 products (Type 6344, 6345)", "<html>Core i3 1.6GHz,<br> 4GB DDR2,<br>320GB,512 MB VGA,<br>Win7</html>"),"Desktop_IBM_1.jpg", authUser));
            panelIBM.add(this.CreateJPanel(new Product(49890, "IBM PC 300GL and PC 300XL products", "<html>Core core2-duo  2.6GHz,<br> 2GB DDR3,<br>500GB,1GB VGA,<br>Win7</html>"),"Desktop_IBM_2.jpg", authUser));
            panelIBM.add(this.CreateJPanel(new Product(38585, "IBM PC 300PL products (Types 6562, 6592, 6862, 6892)", "<html>Core i7 1.6GHz,<br> 6GB DDR3,<br>640GB,1GB VGA<br>,Win7</html>"),"Desktop_IBM_3.jpg", authUser));
            panelIBM.add(this.CreateJPanel(new Product(62000, "IBM PC 300PL products (Types 6565, 6566, 6584, 6594, 6595, 6872, 6890)", "<html>Core i7 1.6GHz,<br> 6GB DDR3,<br>640GB,1GB VGA,<br>Win7</html>"),"Desktop_IBM_4.jpg", authUser));
            return panelIBM;

    }

    JPanel hPDeskPanel (User authUser){
         JPanel panelHP = new JPanel();
            panelHP.add(this.CreateJPanel(new Product(55000, "HP PC  products   d220 ", "<html>Core i7 1.6GHz,<br> 6GB DDR3,<br>640GB,1GB VGA,<br>Dos</html>"),"Desktop_HP_1.jpg", authUser));
            panelHP.add(this.CreateJPanel(new Product(49890, "HP PC  and PC 300XL d325", "<html>Core i3 2.6GHz,<br> 6GB DDR3,<br>640GB,1GB VGA,<br>Dos</html>"),"Desktop_HP_2.jpg", authUser));
            panelHP.add(this.CreateJPanel(new Product(38585, "HP PC  products dc5000", "<html>Core i5 3.2GHz,<br> 4GB DDR3,<br>640GB,1GB VGA,<br>DOs</html>"),"Desktop_HP_3.jpg", authUser));
            panelHP.add(this.CreateJPanel(new Product(62000, "HP PC  products rp5000", "<html>Core i7 1.6GHz,<br> 6GB DDR3,<br>640GB,1GB VGA,<br>Dos</html>"),"Desktop_HP_4.jpg", authUser));
            return panelHP;
    }

    JPanel compaqPanel(User authUser) {
        JPanel panelLaptopCq = new JPanel();
            panelLaptopCq.add(this.CreateJPanel(new Product(65000, " Compaq 620", "<html>Core i3 2.6GHz,<br> 2GB DDR2,<br>320GB,<br>1GB VGA,Dos</html>"),"Laptop_CoQ_1.jpg", authUser));
            panelLaptopCq.add(this.CreateJPanel(new Product(75000, "Compaq 420", "<html>Core i5 2.6GHz,<br> 4GB DDR2,<br>500GB,<br>2GB VGA,Dos</html>"),"Laptop_CoQ_2.jpg", authUser));
            return panelLaptopCq;
    }

    JPanel hardDiskPanel(User authUser){
         JPanel panelHardDisk = new JPanel();
            panelHardDisk.add(this.CreateJPanel(new Product(5880, "Maxtor", "<Html>Internal<br>500 GB</html>"),"HardDisk_1.jpg", authUser));
            panelHardDisk.add(this.CreateJPanel(new Product(13000, "SeaGate", "<Html>External<br>1 TB</html>"),"HardDisk_2.jpg", authUser));
            panelHardDisk.add(this.CreateJPanel(new Product(11500, "Toshiba", "<Html>External<br>1 TB</html>"),"HardDisk_3.jpg", authUser));
            panelHardDisk.add(this.CreateJPanel(new Product(11500, "Samsung", "<Html>External<br>500 GB</html>"),"HardDisk_4.jpg", authUser));
            return panelHardDisk;
    }

    JPanel keyBoardPanel(User authUser){
         JPanel panelkeyBoard = new JPanel();
            panelkeyBoard.add(this.CreateJPanel(new Product(800, "HP", "<Html>Wireless<br>Professional</html>"),"KeyBoard_1.jpg", authUser));
            panelkeyBoard.add(this.CreateJPanel(new Product(1200, "A4 tech", "<Html>Wireless<br>Flexible</html>"),"KeyBoard_2.jpg", authUser));
            panelkeyBoard.add(this.CreateJPanel(new Product(1200, "HP", "<Html>PS/2<br>Classic</html>"),"KeyBoard_3.jpg", authUser));
            panelkeyBoard.add(this.CreateJPanel(new Product(1240, "HP", "<Html>Wireless<br>flexible</html>"),"KeyBoard_4.jpg", authUser));
            return panelkeyBoard;
    }

    JPanel mousePanel(User authUser){
         JPanel panelMouse = new JPanel();
            panelMouse.add(this.CreateJPanel(new Product(850, "Mega Box", "<Html>Optical</html>"),"Mouse_1.jpg", authUser));
            panelMouse.add(this.CreateJPanel(new Product(750, "A4 tech", "<Html>PS/2</html>"),"Mouse_2.jpg", authUser));
            panelMouse.add(this.CreateJPanel(new Product(1050, "Microsoft", "<Html>WireLess</html>"),"Mouse_3.jpg", authUser));
             panelMouse.add(this.CreateJPanel(new Product(1150, "Microsoft", "<Html>WireLess gaming</html>"),"Mouse_4.jpg", authUser));
            return panelMouse;
    }

    JPanel speakerPanel(User authUser){
         JPanel panelSpeaker = new JPanel();

            panelSpeaker.add(this.CreateJPanel(new Product(900, " Creative", "<html>2 channel<br> 600 w</html>"),"Speaker_1.jpg", authUser));
            panelSpeaker.add(this.CreateJPanel(new Product(1500, "Divoom", "<html>2 channel<br> 800 w</html>"),"Speaker_2.jpg", authUser));
            panelSpeaker.add(this.CreateJPanel(new Product(3500, "JBL", "<html>4 channel<br> 800 w</html>"),"Speaker_3.jpg", authUser));
            panelSpeaker.add(this.CreateJPanel(new Product(1500, "Sony", "<html>2 channel<br> 800 w</html>"),"Speaker_4.jpg", authUser));
            return panelSpeaker;
    }

    JPanel mornitorPanel(User authUser){
         JPanel panelMorintor = new JPanel();

            panelMorintor.add(this.CreateJPanel(new Product(12000, "HP", "<html>Aspect Ratio:3M color<br> LED</html"),"Mornitor_1.jpg", authUser));
            panelMorintor.add(this.CreateJPanel(new Product(14990, "PixelView", "<html>Aspect Ratio:3M color<br> LED<</html"),"Mornitor_2.jpg", authUser));
            panelMorintor.add(this.CreateJPanel(new Product(14990, "BenQ", "<html>Aspect Ratio:3M color<br> LCD<</html"),"Mornitor_3.jpg", authUser));
            panelMorintor.add(this.CreateJPanel(new Product(14990, "Samsung", "<html>Aspect Ratio:3M color</html"),"Mornitor_4.jpg", authUser));
            return panelMorintor;
    }

    JPanel motherBoardPanel(User authUser){
         JPanel panelMotherBoard= new JPanel();
            panelMotherBoard.add(this.CreateJPanel(new Product(6250, "FoxConn ", "<HTML>A 780 GM</HTML>"),"MB_1.jpg", authUser));
            panelMotherBoard.add(this.CreateJPanel(new Product(6400, "MSI ", "<HTML>X 68</HTML>"),"MB_2.jpg", authUser));
            panelMotherBoard.add(this.CreateJPanel(new Product(8500, "Intel", "<HTML>LGA 775</HTML>"),"MB_3.jpg", authUser));
            panelMotherBoard.add(this.CreateJPanel(new Product(6500, "Asus ", "<HTML>LGA 795</HTML>"),"MB_4.jpg", authUser));
            return panelMotherBoard;
    }

    JPanel vGAPanel(User authUser){
         JPanel panelVGA= new JPanel();
            panelVGA.add(this.CreateJPanel(new Product(7750, " Nvdia 620 fx", "<HTML>Memory 1 GB</HTML>"),"VGA_1.jpg", authUser));
            panelVGA.add(this.CreateJPanel(new Product(7220, "Nvidia 420 fx ", "<HTML>Memory 512 MB</HTML>"),"VGA_2.jpg", authUser));
            panelVGA.add(this.CreateJPanel(new Product(7220, "ATI Radeon 8500 mx", "<HTML>Memory 512 MB</HTML>"),"VGA_3.jpg", authUser));
            panelVGA.add(this.CreateJPanel(new Product(7220, "ATI Radeon 6500 mx", "<HTML>Memory 256 MB</HTML>"),"VGA_4.jpg", authUser));
            return panelVGA;
    }

    JPanel processorPanel(User authUser){
         JPanel panelProcessor= new JPanel();
            panelProcessor.add(this.CreateJPanel(new Product(8000, "Intel", "<html>i7<br>FSB 800hz</html>"),"Processor_1.jpg", authUser));
            panelProcessor.add(this.CreateJPanel(new Product(5500, "Intel", "<html>i5<br>FSB 1024hz</html>"),"Processor_2.jpg", authUser));
            panelProcessor.add(this.CreateJPanel(new Product(4020, "AMD 64", "<html>i7<br>FSB 800hz</html>"),"Processor_3.jpg", authUser));
            panelProcessor.add(this.CreateJPanel(new Product(5000, "Intel Core 2", "<html>64 bit<br>FSB 800hz</html>"),"Processor_4.jpg", authUser));
            return panelProcessor;
    }

    JPanel casingPanel(User authUser){
         JPanel panelCasing= new JPanel();
            panelCasing.add(this.CreateJPanel(new Product(1000, " Mercury", "<html><br>ATX</html>"),"Casing_1.jpg", authUser));
            panelCasing.add(this.CreateJPanel(new Product(1000, "Sysnon", "<html><br>ATX</html>"),"Casing_2.jpg", authUser));
            panelCasing.add(this.CreateJPanel(new Product(1500, "Apple", "<html><br>ATX</html>"),"Casing_3.jpg", authUser));
            panelCasing.add(this.CreateJPanel(new Product(1250, "Gigabyte", "<html><br>ATX</html>"),"Casing_4.jpg", authUser));
            return panelCasing;
    }

    JPanel ramPanel(User authUser){
         JPanel panelRam = new JPanel();

            panelRam.add(this.CreateJPanel(new Product(3000, "Kingston ", "<html>2GB<br>DDR2</html>"),"Ram_1.jpg", authUser));
            panelRam.add(this.CreateJPanel(new Product(4500, "Gigabyte", "<html>2GB<br>DDR3</html>"),"Ram_2.jpg", authUser));
            panelRam.add(this.CreateJPanel(new Product(6000, "Trancend", "<html>4GB<br>DD/r2</html>"),"Ram_3.jpg", authUser));
            panelRam.add(this.CreateJPanel(new Product(8500, "eSys", "<html>4GB<br>DDR3</html>"),"Ram_4.jpg", authUser));
            return panelRam;
    }
    private JPanel CreateJPanel(Product p,String img,User authUser)
    {
       JPanel panelProduct= new JPanel(new FlowLayout(FlowLayout.CENTER,7,8));
       panelProduct.setPreferredSize(new Dimension(200,250));
       ImageIcon icon = new ImageIcon("src//Images//"+img);
       JLabel label = new JLabel(p.getDescription());

       label.setVerticalTextPosition(JLabel.BOTTOM);
       label.setHorizontalTextPosition(JLabel.CENTER);
       label.setForeground(Color.BLACK);
       label.setIcon(icon);
       label.setForeground(Color.BLUE);
       label.setFont(new Font("Trebuchet", Font.BOLD, 12));
       label.setToolTipText("<HTml>"+p.getName()+"<br> "+p.getDescription());

       JLabel lblprice = new JLabel( "Rs. "+p.getPrice());
       lblprice.setVerticalTextPosition(JLabel.BOTTOM);
       lblprice.setHorizontalTextPosition(JLabel.CENTER);
       JCheckBox jchkBoxHpLap = new JCheckBox("Buy");

       JComboBox jcmbQty = new JComboBox(new Integer[]{1,2,3,4,5,6,7,8,9,10});
       p.setQuantity((Integer)jcmbQty.getSelectedItem());
       jcmbQty.addActionListener(new ComboListener(p));

       jchkBoxHpLap.addItemListener(new MyCheckBoxListener(p,authUser,productSel));

       panelProduct.add(label,BorderLayout.NORTH);
       panelProduct.add(lblprice,BorderLayout.CENTER);
       panelProduct.add(jchkBoxHpLap);
       panelProduct.add(jcmbQty);
       panelProduct.setBorder(new LineBorder(Color.cyan,1));

       return panelProduct;
    }
}

class MyCheckBoxListener implements ItemListener {

    User customer;
    Product product;
    ProductSelection prodSel;

    MyCheckBoxListener(Product p, User authUser,ProductSelection prodSel) {
        customer = authUser;
        this.product = p;
        this.prodSel = prodSel;
    }

    public void itemStateChanged(ItemEvent e) {

        if (e.getStateChange() == ItemEvent.SELECTED)
            customer.purchasedProducts.add(product);
        else
            customer.purchasedProducts.remove(product);

        this.updateJList(customer.purchasedProducts);

    }

    void updateJList(ArrayList<Product> arr)
    {
        prodSel.listmodel.clear();
        double dblAmount = 0.0;

        for (Product p : arr)
        {
           prodSel.listmodel.addElement(p.getName()+" "+p.getPrice()+" x"+p.getQuantity());
           dblAmount += p.getPrice()*p.getQuantity();
        }

          prodSel.lblAmount.setText("Total Amount : "+dblAmount);
          prodSel.Amount = dblAmount;
    }

}
class ComboListener implements ActionListener{
    Product selPro;
    ComboListener(Product p){
            this.selPro = p;
    }
    public void actionPerformed(ActionEvent e) {
         JComboBox jcmbQty = (JComboBox)e.getSource();
         selPro.setQuantity((Integer)jcmbQty.getSelectedItem());
    }

}

package OnlineShop;

/**
 *
 * @author Roshan
 */
public class Product {

   private double price;
   private String name;
   private String description;
   private int    quantity;
    Product(double price , String name,String description){
        this.price = price;
        this.name = name;
        this.description = description;

    }
    protected void setQuantity(int qnt){
        this.quantity = qnt;
    }
    protected double getPrice(){
        return this.price;
    }
    protected String getName(){
        return this.name;
    }
    protected String getDescription(){
        return this.description;
    }
    protected int getQuantity(){
        return this.quantity;
    }

}










package OnlineShop;

/**
 *
 * @author Roshan
 */
import java.awt.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class ProductSelection {

    protected User buyer;
    protected JTree tree;
    protected JFrame frame;
    protected JList purchaseProduct;
    protected JPanel currentPanel;
    protected JPanel jplLaptopHP;
    protected JPanel jplLaptopCQ;
    protected JPanel jplLaptopDell;
    protected JPanel jplDesktopIBM;
    protected JPanel jplDesktopHP;
    protected JPanel jplHardDisk;
    protected JPanel jplMornitor;
    protected JPanel jplMouse;
    protected JPanel jplSpeaker;
    protected JPanel jplKeyBoard;
    protected JPanel jplMotherBoard;
    protected JPanel jplVGA;
    protected JPanel jplProcessor;
    protected JPanel jplRAM;
    protected JPanel jplCasing;
    protected DefaultListModel listmodel;
    protected JLabel lblAmount;
    protected JPanel jpnlAmount;
    protected double Amount;
    private javax.swing.JDialog jDialog1;

    ProductSelection(User authUser) {
        this.buyer = authUser;
        currentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 80, 40));
        ImagePanel lp = new ImagePanel(this);
        this.jplLaptopHP = lp.hpPanel(authUser);
        this.jplLaptopCQ = lp.compaqPanel(authUser);
        this.jplLaptopDell = lp.dellPanel(authUser);
        this.jplDesktopIBM = lp.iBMDeskPanel(authUser);
        this.jplDesktopHP = lp.hPDeskPanel(authUser);
        this.jplKeyBoard = lp.keyBoardPanel(authUser);
        this.jplMornitor = lp.mornitorPanel(authUser);
        this.jplMouse = lp.mousePanel(authUser);
        this.jplSpeaker = lp.speakerPanel(authUser);
        this.jplMotherBoard = lp.motherBoardPanel(authUser);
        this.jplHardDisk = lp.hardDiskPanel(authUser);
        this.jplVGA = lp.vGAPanel(authUser);
        this.jplProcessor = lp.processorPanel(authUser);
        this.jplRAM = lp.ramPanel(authUser);
        this.jplCasing = lp.casingPanel(authUser);
    }

    void display() {
        User ObjUser = new User();
        frame = new JFrame("WELCOME " + ObjUser.getLoginName().toUpperCase() + " !");
        JScrollPane scroll = new JScrollPane();

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("ECSE501 Computers");
        DefaultMutableTreeNode nodeLaptop = new DefaultMutableTreeNode("Laptop");
        root.add(nodeLaptop);
        //****************************
        DefaultMutableTreeNode nodeLaptopHp = new DefaultMutableTreeNode(" HP");
        DefaultMutableTreeNode nodeLaptopCq = new DefaultMutableTreeNode(" Compaq");
        DefaultMutableTreeNode nodeLaptopDell = new DefaultMutableTreeNode(" Dell");
        nodeLaptop.insert(nodeLaptopHp, 0);
        nodeLaptop.insert(nodeLaptopCq, 1);
        nodeLaptop.insert(nodeLaptopDell, 2);

        //*******************************
        DefaultMutableTreeNode nodeDesktop = new DefaultMutableTreeNode("Desktop");
        DefaultMutableTreeNode nodeDeskTopIBM = new DefaultMutableTreeNode("Desk-IBM");
        DefaultMutableTreeNode nodeDeskTopHp = new DefaultMutableTreeNode("Desk-HP");
        nodeDesktop.insert(nodeDeskTopIBM, 0);
        nodeDesktop.insert(nodeDeskTopHp, 1);
        root.add(nodeDesktop);
        //*****************************************
        DefaultMutableTreeNode nodeAccessories = new DefaultMutableTreeNode("Accessories");
        DefaultMutableTreeNode nodeKeyBoard = new DefaultMutableTreeNode("KeyBoard");
        DefaultMutableTreeNode nodeMornitor = new DefaultMutableTreeNode("Mornitor");
        DefaultMutableTreeNode nodeMouse = new DefaultMutableTreeNode("Mouse");
        DefaultMutableTreeNode nodeSpeaker = new DefaultMutableTreeNode("Speaker");

        nodeAccessories.insert(nodeKeyBoard, 0);
        nodeAccessories.insert(nodeMornitor, 1);
        nodeAccessories.insert(nodeMouse, 2);
        nodeAccessories.insert(nodeSpeaker, 3);

        root.add(nodeAccessories);
        DefaultMutableTreeNode nodeAssemble = new DefaultMutableTreeNode("Assemble");
        DefaultMutableTreeNode nodeMotherBoard = new DefaultMutableTreeNode("MotherBoard");

        DefaultMutableTreeNode nodeHardDisk = new DefaultMutableTreeNode("HardDisk");
        DefaultMutableTreeNode nodeVGA = new DefaultMutableTreeNode("VGA");
        DefaultMutableTreeNode nodeProcessor = new DefaultMutableTreeNode("Processor");
        DefaultMutableTreeNode nodeCasing = new DefaultMutableTreeNode("Casing");
        DefaultMutableTreeNode nodeRAM = new DefaultMutableTreeNode("RAM");

        nodeAssemble.insert(nodeMotherBoard, 0);
        nodeAssemble.insert(nodeHardDisk, 1);
        nodeAssemble.insert(nodeVGA, 2);
        nodeAssemble.insert(nodeProcessor, 3);
        nodeAssemble.insert(nodeRAM, 4);
        nodeAssemble.insert(nodeCasing, 5);

        root.add(nodeAssemble);

        //*******************************************

        JPanel jpnlTree = new JPanel();
        tree = new JTree(root);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);


        tree.addTreeSelectionListener(new MyTreeSelectionListener(this, buyer));


        jpnlTree.add(new JScrollPane(tree));
        jpnlTree.setBackground(Color.LIGHT_GRAY);
        jpnlTree.setSize(new Dimension(100, 500));
        listmodel = new DefaultListModel();
        purchaseProduct = new JList(listmodel);

        purchaseProduct.setPreferredSize(new Dimension(240, 490));
        purchaseProduct.setLayoutOrientation(JList.VERTICAL);
        purchaseProduct.setBorder(new LineBorder(Color.GRAY, 3));
        JPanel jpnlList = new JPanel(new FlowLayout(FlowLayout.CENTER, 40, 20));
        jpnlList.setBorder(new LineBorder(Color.DARK_GRAY, 3));

        jpnlList.setPreferredSize(new Dimension(265, JFrame.HEIGHT));
        JLabel lblPurchase = new JLabel("Your Cart");
        lblPurchase.setFont(new Font("Calibri", Font.BOLD, 15));
        lblPurchase.setForeground(Color.darkGray);
        JButton btnPurchase = new JButton("Purchase");
        btnPurchase.setActionCommand("Purchase");
        btnPurchase.addActionListener(new MyRemActionListener(this));

        jpnlList.add(lblPurchase);

        JScrollPane scrollPane = new JScrollPane(purchaseProduct);
        scrollPane.setPreferredSize(new Dimension(250, 490));
        jpnlList.add(scrollPane, BorderLayout.CENTER);

        //jpnlList.add(new JScrollPane(purchaseProduct));


        jpnlList.add(btnPurchase);
        this.lblAmount = new JLabel("here  i am ");

        lblAmount.setFont(new Font("Calibri", Font.BOLD, 14));


        this.lblAmount = new JLabel();
        jpnlList.setBackground(Color.LIGHT_GRAY);

        jpnlAmount = new JPanel(new FlowLayout(FlowLayout.CENTER, 80, 40));
        jpnlAmount.add(lblAmount);
        jpnlAmount.setBorder(new LineBorder(Color.DARK_GRAY, 3));

        JPanel jpnlgreet = new JPanel();
        jpnlgreet.setBackground(Color.GREEN);
        JLabel lblGreet = new JLabel("WELCOME TO ECSE501 COMPUTERS ");
        lblGreet.setFont(new Font("Calibri", Font.BOLD, 16));
        jpnlgreet.add(lblGreet);
        JLabel lblBanner = new JLabel();
        lblBanner.setIcon(new ImageIcon("src//Images//Banner.jpg"));

        currentPanel.add(lblBanner, BorderLayout.CENTER);
        frame.getContentPane().add(jpnlList, BorderLayout.EAST);
        frame.getContentPane().add(currentPanel, BorderLayout.CENTER);
        frame.getContentPane().add(jpnlgreet, BorderLayout.NORTH);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.getContentPane().add(jpnlTree, BorderLayout.WEST);
        frame.getContentPane().add(jpnlAmount, BorderLayout.PAGE_END);
        frame.setSize(1250, 900);
        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = frame.getSize().width;
        int h = frame.getSize().height;
        int x = (dim.width - w) / 2;
        int y = (dim.height - h) / 2;

        // Move the window
        frame.setLocation(x, y);

    }
}

class MyTreeSelectionListener implements TreeSelectionListener {

    ProductSelection tr;
    User authUser;

    MyTreeSelectionListener(ProductSelection tr, User authUser) {
        this.tr = tr;
        this.authUser = authUser;

    }

    public void valueChanged(TreeSelectionEvent e) {

        try {
            if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("HP")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplLaptopHP);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 901);

            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Compaq")) {
                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplLaptopCQ);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1251, 901);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Dell")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplLaptopDell);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1251, 900);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Desk-IBM")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplDesktopHP);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1252, 902);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Desk-HP")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplDesktopIBM);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1253, 901);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("KeyBoard")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplKeyBoard);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1254, 900);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Mornitor")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplMornitor);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 905);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Mouse")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplMouse);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 906);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Speaker")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplSpeaker);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 907);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("MotherBoard")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplMotherBoard);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 910);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("HardDisk")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplHardDisk);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 901);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("VGA")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplVGA);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 902);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Processor")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplProcessor);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1250, 915);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("RAM")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplRAM);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1251, 901);
            } else if (tr.tree.getLastSelectedPathComponent().toString().trim().equals("Casing")) {

                tr.currentPanel.removeAll();
                tr.currentPanel.add(tr.jplCasing);
                tr.currentPanel.invalidate();
                tr.currentPanel.validate();
                tr.frame.setSize(1251, 902);
            }
        } catch (Exception ex) {
        }

    }
}

class MyRemActionListener implements ActionListener {

    ProductSelection prodSel;

    MyRemActionListener(ProductSelection prodSel) {
        this.prodSel = prodSel;
    }

    public void actionPerformed(ActionEvent e) {

        if (e.getActionCommand().equals("Purchase")) {
            if (!prodSel.listmodel.isEmpty()) {
                Object obj[] = {"Pay", "Back"};
                Object Pay[] = {"Credi Card", "Cash"};
                int showOptionObj = JOptionPane.showOptionDialog(null, "Please, select your Option", "Option", JOptionPane.YES_NO_OPTION, JOptionPane.OK_OPTION, null, obj, obj[0]);
                boolean isback = false;

                switch (showOptionObj) {
                    case 0:
                        prodSel.frame.setVisible(true);
                        JOptionPane.showMessageDialog(null, "<html> <b>Your Amount is " + prodSel.Amount + "</b></html>");
                        //System.exit(0);
                        break;
                    case 1:
                        prodSel.frame.setVisible(true);
                        isback = true;
                        break;
                    default:
                        System.exit(0);
                }

                if (!isback) {
                    int showOptionPay = JOptionPane.showOptionDialog(null, "Please, select Payment Method", "Payment", JOptionPane.YES_NO_OPTION, JOptionPane.OK_OPTION, null, Pay, Pay[0]);

                    switch (showOptionPay) {
                        case 0:
                            prodSel.frame.setVisible(true);
                            JOptionPane.showInputDialog(null, "Enter Credit Card Number", "PayPal", JOptionPane.PLAIN_MESSAGE);
                            JOptionPane.showMessageDialog(null, "Thank You! your items will be deliverd with in next two working days.", "Credited", JOptionPane.INFORMATION_MESSAGE);
                            System.exit(0);
                            break;
                        case 1:
                            prodSel.frame.setVisible(true);
                            JOptionPane.showMessageDialog(null, "Thank You! your items will be deliverd with in next two working days.", "Receipt", JOptionPane.INFORMATION_MESSAGE);
                            System.exit(0);
                            break;
                        default:
                            System.exit(0);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Your Cart is Empty, Please select items to purchase", "Empty Cart", JOptionPane.ERROR_MESSAGE);
            }

        }


    }
}
package OnlineShop;
import java.util.ArrayList;


/**
 *
 * @author Roshan
 */

public class User {
     String password = "admin123";
     String loginName = "admin";

    ArrayList<Product> purchasedProducts = new ArrayList<Product>();

    protected String getPassword (){
        return this.password;
    }
    protected String getLoginName(){
        return this.loginName;
    }
}