Package ui

Source Code of ui.PetStoreProductView$ProductInfo

/*
PetStoreProductView.java
*
* Copyright 2001-2004 The Apache Software Foundation.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/package ui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.math.BigDecimal;
import java.net.URL;
import java.rmi.RemoteException;

import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.ToolTipManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;

import org.apache.beehive.petstore.InvalidIdentifierException;
import org.apache.beehive.petstore.PetstoreInventoryManager;
import org.apache.beehive.samples.petstore.model.Item;
import org.apache.beehive.samples.petstore.model.ws.Category;
import org.apache.beehive.samples.petstore.model.ws.Product;



public class PetStoreProductView extends JPanel implements
        TreeSelectionListener {
    private static final long serialVersionUID = 1L;

    PetstoreInventoryManager store;

    private JTree tree;

    private URL helpURL;

    private static boolean DEBUG = false;

    private ProductDetailModel currentProductItemModel;

    private ProductItemView currentProductItemView;

    public PetStoreProductView(PetstoreInventoryManager store) {
        super(new GridLayout(1, 0));

        this.store = store;

        //Create the nodes.
        DefaultMutableTreeNode storeNode = new DefaultMutableTreeNode(
                "Store name here");

        DefaultMutableTreeNode storeInfoNode = new DefaultMutableTreeNode(
                new StoreInfo());
        storeNode.add(storeInfoNode);

        DefaultMutableTreeNode productsNode = new DefaultMutableTreeNode(
                new StoreProductInfo());
        storeNode.add(productsNode);

        //Create a tree that allows one selection at a time.
        tree = new JTree(storeNode);
        tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);

        //Enable tool tips.
        ToolTipManager.sharedInstance().registerComponent(tree);

        tree.setCellRenderer(new MyRenderer());

        //Listen for when the selection changes.
        tree.addTreeSelectionListener(this);

        //Create the scroll pane and add the tree to it.
        JScrollPane treeView = new JScrollPane(tree);

        currentProductItemView = new ProductItemView();

        //Add the scroll pane to this panel.
        add(currentProductItemView);

        //Add the scroll panes to a split pane.
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(treeView);
        splitPane.setRightComponent(currentProductItemView);

        Dimension minimumSize = new Dimension(100, 50);
        treeView.setMinimumSize(minimumSize);
        splitPane.setDividerLocation(100); //XXX: ignored in some releases
        //of Swing. bug 4101306
        //workaround for bug 4101306:
        //treeView.setPreferredSize(new Dimension(100, 100));

        splitPane.setPreferredSize(new Dimension(500, 300));

        //Add the split pane to this panel.
        add(splitPane);
    }

    /** Required by TreeSelectionListener interface. */
    public void valueChanged(TreeSelectionEvent event) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
                .getLastSelectedPathComponent();

        if (node == null)
            return;

        Object nodeInfo = node.getUserObject();
       try {
            if (StoreProductInfo.class.isInstance(nodeInfo)) {
                node.removeAllChildren();
                System.out.println("Get all product catagories.");
                Category[] categories = store.listCategories();
                for (int i = 0; i < categories.length; i++) {
                    node.add(new DefaultMutableTreeNode(
                            new ProductCategoryInfo(categories[i])));
                }

            } else if (ProductCategoryInfo.class.isInstance(nodeInfo)) {
                ProductCategoryInfo info = (ProductCategoryInfo) nodeInfo;
                System.out.println("Get all products in: "
                        + info.getCategory().getName() + " catagory.");
                node.removeAllChildren();
                Product[] products = store.listProducts(info.getCategory()
                        .getCatId());
                for (int i = 0; i < products.length; i++) {
                    node.add(new DefaultMutableTreeNode(new ProductInfo(
                            products[i])));
                }

            } else if (ProductInfo.class.isInstance(nodeInfo)) {
                ProductInfo info = (ProductInfo) nodeInfo;
                System.out.println("Get product information for: "
                        + info.getProduct().getName());
                currentProductItemView.setProductItem(info.getProduct());

            } else if (StoreInfo.class.isInstance(nodeInfo)) {
               
                JOptionPane.showMessageDialog(this, "TBD... Get store information.", "TBD",
                        JOptionPane.INFORMATION_MESSAGE);              
           } else {
                System.out.println("Unknown node type!");
            }
        } catch (RemoteException e) {
            String message;
            if(null != e.getCause()) message = e.getCause().getMessage();
            else message = e.getMessage();
            JOptionPane.showMessageDialog(this,message, "Exception",
                    JOptionPane.ERROR_MESSAGE);

            e.printStackTrace();
        }

    }
   
    protected Icon getImageIcon(Image image) {
        if(null == image) return new ImageIcon(createImage("images/default.gif"));
        else return new ImageIcon(image);
    }
    protected Image createImage(String path) {
        //java.net.URL imgURL = new URL(path); // this.getClass().getResource(path);
       // System.out.println("create image for: " + imgURL);
       // return Toolkit.getDefaultToolkit().createImage(imgURL);
       return Toolkit.getDefaultToolkit().createImage(path);
   }
   
    private Image scaleToIcon(Image image) {
        if(null == imageimage = createImage("images/default.gif");
        return image.getScaledInstance(-1, 40, Image.SCALE_DEFAULT);
    }

   

    class ProductItemView extends JPanel {

        private static final long serialVersionUID = 1L;

        private JTable table = new JTable();

        private JLabel productIcon = new JLabel();

        private JLabel productName = new JLabel();

        /**
         * 
         */
        public ProductItemView() {
            super();
            setBackground(Color.WHITE);
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            productName.setAlignmentX(CENTER_ALIGNMENT);
            productIcon.setAlignmentX(CENTER_ALIGNMENT);
            add(productName);
            add(productIcon);

            add(table);

            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);

            add(scrollPane);
            Dimension minimumSize = new Dimension(100, 50);
            scrollPane.setMinimumSize(minimumSize);

        }

        public void setProductItem(Product product) {

            try {
                productIcon.setIcon(getImageIcon(product.getAttachedImage()));
                productName.setText(product.getName());
                table.setModel(new ProductDetailModel(product));
             } catch (RemoteException e) {
                String message;
                if(null != e.getCause()) message = e.getCause().getMessage();
                else message = e.getMessage();
                JOptionPane.showMessageDialog(this, message,
                        "Exception", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }

        }
    }

    class ProductDetailModel extends AbstractTableModel {
        private static final long serialVersionUID = 1L;

        private String[] columnNames = { "itemId", "Product Id", "atr1",
                "attr2", "attr3", "attr4", "attr5", "List Price", "Quantity",
                "Supplier Id", "Unit Cost", "Status", "Add to Stock" };

        Item[] items = null;

        public ProductDetailModel(Product product) throws RemoteException {
            items = store.listItems(product.getProductId());
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            if (items == null)
                return 0;
            return items.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            Item curItem = items[row];
            if (col == 0)
                return curItem.getItemId();
            else if (col == 1)
                return curItem.getProductId();
            else if (col == 2)
                return curItem.getAttr1();
            else if (col == 3)
                return curItem.getAttr2();
            else if (col == 4)
                return curItem.getAttr3();
            else if (col == 5)
                return curItem.getAttr4();
            else if (col == 6)
                return curItem.getAttr5();
            else if (col == 7)
                return curItem.getListPrice();
            else if (col == 8)
                return "" + curItem.getQty();
            else if (col == 9)
                return "" + curItem.getSupplier();
            else if (col == 10)
                return curItem.getUnitCost();
            else if (col == 11)
                return curItem.getStatus();
            else if (col == 12)
                return "";
            else
                return "Unknown Column";
        }

        public boolean isCellEditable(int row, int col) {
            if (col == 7 || col == 12)
                return true;
            else
                return false;
        }

        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                        + " to " + value + " (an instance of "
                        + value.getClass() + ")");
            }

            String itemId = items[row].getItemId();
            String productId = items[row].getProductId();
            try {
                if (col == 7)
                    store.setItemListPrice(itemId, new BigDecimal(
                            (String) value));
                else if (col == 12)
                    store.restockItem(itemId, Integer.parseInt((String) value));

                items = store.listItems(productId); // refresh model
            } catch (InvalidIdentifierException e) {
                  e.printStackTrace();
            } catch (NumberFormatException e) {
                 e.printStackTrace();
            } catch (RemoteException e) {
                 e.printStackTrace();
            }

        }
    }

    private class StoreProductInfo {
        public String toString() {
            return "Products";
        }
    }

    private class StoreInfo {
        public String toString() {
            return "Store";
        }
    }

    private class ProductCategoryInfo {
        Category category;

        /**
         * @return Returns the catagory.
         */
        public Category getCategory() {
            return category;
        }

        /**
         * @param catagory
         */
        public ProductCategoryInfo(Category category) {
            super();
            this.category = category;
            System.out
                    .println("build category info for: " + category.getName());
        }

        public String toString() {
            return category.getName();
        }
    }

    private class ProductInfo {
        Product product;

        /**
         * @return Returns the product.
         */
        public Product getProduct() {
            return product;
        }

        /**
         * @param product
         */
        public ProductInfo(Product product) {
            super();
            this.product = product;
        }

        public String toString() {
            return product.getName();
        }
    }


    private class MyRenderer extends DefaultTreeCellRenderer {
        private static final long serialVersionUID = 1L;

        Icon tutorialIcon;

        public MyRenderer() {

        }

        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean sel, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {

            super.getTreeCellRendererComponent(tree, value, sel, expanded,
                    leaf, row, hasFocus);

            setIcon(getNodeIcon(value));
            setToolTipText(getNodeToolTip(value));
            setFont(new Font("serif", Font.BOLD, 15));
            return this;
        }

        /**
         * @param value
         * @return
         */
        private String getNodeToolTip(Object value) {
            Object nodeInfo = ((DefaultMutableTreeNode) value).getUserObject();
            if (StoreProductInfo.class.isInstance(nodeInfo)) {
                return "Click to get list of Products";
            } else if (StoreInfo.class.isInstance(nodeInfo)) {
                return "Click to get store information";
            } else if (ProductCategoryInfo.class.isInstance(nodeInfo)) {
                return ((ProductCategoryInfo) nodeInfo).getCategory()
                        .getDescription();
            } else if (ProductInfo.class.isInstance(nodeInfo)) {
                return ((ProductInfo) nodeInfo).getProduct().getDescription();

            } else {
                return null;
            }
        }

        /**
         * @param value
         * @return
         */

        private Icon getNodeIcon(Object value) {

            Object nodeInfo = ((DefaultMutableTreeNode) value).getUserObject();
            if (StoreProductInfo.class.isInstance(nodeInfo)) {
                return null;
            } else if (ProductCategoryInfo.class.isInstance(nodeInfo)) {
                 return getImageIcon(((ProductCategoryInfo) nodeInfo).getCategory().getAttachedImage());

            } else if (ProductInfo.class.isInstance(nodeInfo)) {
                return new ImageIcon(scaleToIcon(((ProductInfo) nodeInfo)
                        .getProduct().getAttachedImage()));
            } else {
                return null;
            }
        }


    }
}
TOP

Related Classes of ui.PetStoreProductView$ProductInfo

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.