Presentation is loading. Please wait.

Presentation is loading. Please wait.

Practice Solutions.

Similar presentations


Presentation on theme: "Practice Solutions."— Presentation transcript:

1 Practice Solutions

2 Oracle 10g: Java Programming C-2
Company.java package oe; public class Company extends Customer { private String contact; private int discount; public Company(String aName, String aAddress, String aPhone, String aContact, int aDiscount) super(aName, aAddress, aPhone); contact = aContact; discount = aDiscount; } public String getContact() return contact; public void setContact(String newContact) contact = newContact; public int getDiscount() return discount; public void setDiscount(int newDiscount) discount = newDiscount; public String toString() return super.toString() + " (" + contact + ", " + discount + "%)"; Order Entry Solution Oracle 10g: Java Programming C-2

3 Oracle 10g: Java Programming C-3
Customer.java package oe; public class Customer { private static int nextCustomerId = 0; private int id; private String name; private String address; private String phone; public Customer() nextCustomerId++; setId(nextCustomerId); } public Customer(String theName, String theAddress, String thePhone) this(); name = theName; address = theAddress; phone = thePhone; public int getId() return id; public String getName() return name; public String getAddress() return address; public String getPhone() return phone; Order Entry Solution Oracle 10g: Java Programming C-3

4 Oracle 10g: Java Programming C-4
Customer.java (continued) public void setId(int newId) { id = newId; } public void setName(String newName) name = newName; public void setAddress(String newAddress) address = newAddress; public void setPhone(String newPhone) phone = newPhone; public String toString() return "[" + Util.getClassName(this) + "] " + id + " " + name + " " + address + " " + phone; Order Entry Solution Oracle 10g: Java Programming C-4

5 Oracle 10g: Java Programming C-5
DataMan.java package oe; import java.util.HashMap; public class DataMan { private static class ProductMap extends HashMap public void add(Product p) String key = Integer.toString(p.getId()); put(key, p); } private static Customer[] customers = null; private static ProductMap products = null; public static void buildCustomers() if (customers != null) return; customers = new Customer[6]; customers[0] = new Customer("Gary Williams", "Houston, TX", " "); customers[1] = new Customer("Lynn Munsinger", "Orlando, FL", " "); customers[2] = new Customer("Rachael O'leary", "Brisbane, QLD", " "); customers[3] = new Customer("Tony Obermeit", "Brisbane, QLD", " "); customers[4] = new Company("Oracle Corporation", "Redwood Shores, CA", "800-ORACLE-1", "Larry Ellison", 20); customers[5] = new Individual("Mel Gibson", "Hollywood, CA", "213.MEL.GIBSON", "MAD-MAX"); Order Entry Solution Oracle 10g: Java Programming C-5

6 Oracle 10g: Java Programming C-6
DataMan.java (continued) public static void buildProducts() { if (products != null) return; products = new ProductMap(); products.add(new Hardware("SDRAM MB", null, 299.0)); products.add(new Hardware("GP 800x600", null, 48.0)); products.add(new Software("Spreadsheet-SSP/V2.0", null, 45.0)); products.add(new Software("Word Processing-SWP/V4.5", null, 65.0)); products.add(new Manual("Manual-Vision OS/2x +", null, 125.0)); } public static Customer findCustomerById(int custId) throws NotFoundException Customer c = null; for (int i = 0; i < customers.length; i++) if (customers[i].getId() == custId) c = customers[i]; break; if (c == null) throw new NotFoundException("Customer with id " + custId + " does not exist"); return c; Order Entry Solution Oracle 10g: Java Programming C-6

7 Oracle 10g: Java Programming C-7
DataMan.java (continued) public static Product findProductById(int id) throws NotFoundException { String key = Integer.toString(id); Product product = (Product) products.get(key); if (product == null) throw new NotFoundException("Product with id " + id + " is not found"); } return product; static buildCustomers(); buildProducts(); Order Entry Solution Oracle 10g: Java Programming C-7

8 Oracle 10g: Java Programming C-8
Hardware.java package oe; public class Hardware extends Product implements Taxable { private int warrantyPeriod = 6; public Hardware(String name, String desc, double price) setName(name); setDescription(desc); setRetailPrice(price); } public int getWarrantyPeriod() return warrantyPeriod; public void setWarrantyPeriod(int newWarrantyPeriod) warrantyPeriod = newWarrantyPeriod; public double getTax(double amount) return amount * TAX_RATE; Order Entry Solution Oracle 10g: Java Programming C-8

9 Oracle 10g: Java Programming C-9
Individual.java package oe; public class Individual extends Customer { private String licNumber; public Individual(String aName, String aAddress, String aPhone, String aLicNumber) super(aName, aAddress, aPhone); licNumber = aLicNumber; } public String getLicNumber() return licNumber; public void setLicNumber(String newLicNumber) licNumber = newLicNumber; public String toString() return super.toString() + " (" + licNumber + ")"; Order Entry Solution Oracle 10g: Java Programming C-9

10 Oracle 10g: Java Programming C-10
Manual.java package oe; public class Manual extends Product { private String publisher = "Oradev Press"; public Manual(String name, String desc, double price) setName(name); setDescription(desc); setRetailPrice(price); } public String getPublisher() return publisher; public void setPublisher(String newPublisher) publisher = newPublisher; Order Entry Solution Oracle 10g: Java Programming C-10

11 Oracle 10g: Java Programming C-11
NotFoundException.java package oe; public class NotFoundException extends Exception { public NotFoundException(String message) super(message); } Order Entry Solution Oracle 10g: Java Programming C-11

12 Oracle 10g: Java Programming C-12
Order.java package oe; import java.util.Date; import java.util.Calendar; import java.text.MessageFormat; import java.util.Vector; import java.util.Enumeration; import javax.swing.DefaultListModel; public class Order { private static int nextOrderId = 100; private int id; private Date orderDate; private String shipMode; private double orderTotal; private String status; private Customer customer; //private Vector items; private DefaultListModel items; public Order() id = nextOrderId++; orderTotal = 0.0; orderDate = new Date(); //items = new Vector(10); items = new DefaultListModel(); } public Order(Date newOrderDate, String newShipMode) this(); orderDate = newOrderDate; shipMode = newShipMode; Order Entry Solution Oracle 10g: Java Programming C-12

13 Oracle 10g: Java Programming C-13
Order.java (continued) public int getId() { return id; } public Date getOrderDate() return orderDate; public String getShipDate(char region) int daysToShip = Util.getDaysToShip(region); Calendar c = Calendar.getInstance(); c.setTime(orderDate); c.add(Calendar.DAY_OF_MONTH, daysToShip); return c.getTime().toString(); public String getShipMode() return shipMode; public double getOrderTotal() return orderTotal; public String getstatus() return status; public void setId(int newId) id = newId; Order Entry Solution Oracle 10g: Java Programming C-13

14 Oracle 10g: Java Programming C-14
Order.java (continued) public void setOrderDate(int d, int m, int y) { int daysInMonth = Util.lastDayInMonth(m, y); if (d > 0 && d <= daysInMonth) if ((m > 0 && m <= 12) && (y > 0)) Calendar c = Calendar.getInstance(); c.set(y, m - 1, d); orderDate = c.getTime(); } public void setOrderDate(Date newOrderDate) orderDate = newOrderDate; public void setShipMode(String newShipMode) shipMode = newShipMode; public void setOrderTotal(double newOrderTotal) orderTotal = newOrderTotal; public void setStatus(String newStatus) status = newStatus; public Customer getCustomer() return customer; Order Entry Solution Oracle 10g: Java Programming C-14

15 Oracle 10g: Java Programming C-15
Order.java (continued) public void setCustomer(Customer newCustomer) { customer = newCustomer; } public String toString() /* // For Les08 lab 4a. return "Order: " + id + " Date: " + Util.toDateString(orderDate) + " Shipped: " + shipMode + " (" + Util.toMoney(getOrderTotal()) + ")"; */ Object[] msgVals = { new Integer(id), Util.toDateString(orderDate), shipMode, Util.toMoney(getOrderTotal()) }; return MessageFormat.format("Order: {0} Date: {1} Shipped: {2} (Total: {3})", msgVals); public void addOrderItem(int productId) OrderItem item = null; boolean productFound = false; for (int i = 0; i < items.size() && !productFound; i++) item = (OrderItem) items.elementAt(i); productFound = (item.getProduct().getId() == productId); if (productFound) item.setQuantity(item.getQuantity() + 1); else Order Entry Solution Oracle 10g: Java Programming C-15

16 Oracle 10g: Java Programming C-16
Order.java (continued) try { Product p = DataMan.findProductById(productId); item = new OrderItem(p); items.addElement(item); item.setLineNbr(items.size()); } catch (NotFoundException e) System.out.println("Error: " + e.getMessage()); e.printStackTrace(); return; orderTotal += item.getUnitPrice(); public void removeOrderItem(int productId) OrderItem item = null; int idx = 0; for (int i = 0; i < items.size(); i++) item = (OrderItem) items.elementAt(i); idx = i; if (item.getProduct().getId() == productId) item.setQuantity(item.getQuantity() - 1); if (item.getQuantity() == 0) items.removeElementAt(idx); for (; idx < items.size(); idx++) item = (OrderItem) items.elementAt(idx); item.setLineNbr(idx+1); orderTotal -= item.getUnitPrice(); Order Entry Solution Oracle 10g: Java Programming C-16

17 Oracle 10g: Java Programming C-17
Order.java (continued) public void showOrder() { double taxTotal = 0.0; System.out.println(toString()); if (customer != null) System.out.println("Customer: " + customer); } System.out.println("Items:"); for (Enumeration e = items.elements(); e.hasMoreElements(); ) OrderItem item = (OrderItem) e.nextElement(); taxTotal += item.getTax(); System.out.println(item.toString()); System.out.println("Total tax: " + Util.toMoney(taxTotal)); System.out.println("Order total including tax: " + Util.toMoney(orderTotal + taxTotal)); System.out.println(); public DefaultListModel getModel() return items; public double getTax() double totalTax = 0.0; totalTax += item.getTax(); return totalTax; Order Entry Solution Oracle 10g: Java Programming C-17

18 Oracle 10g: Java Programming C-18
OrderEntry.java package oe; import java.util.Date; import javax.swing.UIManager; public class OrderEntry { public static void main(String[] args) try UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } OrderEntryMDIFrame frame = new OrderEntryMDIFrame(); frame.setVisible(true); public static void test1(String[] args) Order order = new Order(); double orderTotal; boolean exceedsLimit; double taxRate = ; double taxValue; System.out.println("Order Entry Application"); orderTotal = order.getOrderTotal(); System.out.println("Order Total: " + orderTotal); taxValue = orderTotal * taxRate; System.out.println("Tax Value: " + taxValue); orderTotal += taxValue; System.out.println("Final Total: " + orderTotal); exceedsLimit = orderTotal > 10.00; System.out.println("Total Exceeds $10.00: " + exceedsLimit); Order Entry Solution Oracle 10g: Java Programming C-18

19 Oracle 10g: Java Programming C-19
OrderEntry.java (continued) // order.setOrderDate(27, 1, 2001); order.setOrderDate(27, 2, 2001); char region = 'A'; String shipDate = order.getShipDate(region); System.out.println("Order Date: " + order.getOrderDate()); System.out.println("Days till shipping: " + Util.getDaysToShip(region)); System.out.println("Expected Ship Date: " + shipDate); try { System.out.println("\nCustomers:"); System.out.println(DataMan.findCustomerById(1).toString()); System.out.println(DataMan.findCustomerById(2)); order.setCustomer(DataMan.findCustomerById(5)); order.addOrderItem(2001); order.addOrderItem(2002); order.showOrder(); order.removeOrderItem(2001); order.removeOrderItem(2002); // Order order2 = new Order(new Date(), "overnight"); Order order2 = new Order(Util.getDate(7, 3, 2002), "overnight"); order2.setCustomer(DataMan.findCustomerById(6)); order2.showOrder(); for (int i = 0; i < args.length; i++) int custId = Integer.parseInt(args[i]); System.out.println("Arg: " + custId + " is: " + DataMan.findCustomerById(custId)); } System.out.println("Product id: " + DataMan.findProductById(2001)); catch (NotFoundException e) System.out.println("Error: " + e.getMessage()); e.printStackTrace(); Order Entry Solution Oracle 10g: Java Programming C-19

20 Oracle 10g: Java Programming C-20
OrderEntryFrame.java package oe; import javax.swing.JInternalFrame; import java.awt.BorderLayout; import javax.swing.JPanel; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import javax.swing.JScrollPane; import javax.swing.JLabel; import java.awt.Rectangle; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Color; import javax.swing.JList; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; public class OrderEntryFrame extends JInternalFrame { BorderLayout borderLayout1 = new BorderLayout(); JPanel jPanel1 = new JPanel(); GridLayout gridLayout1 = new GridLayout(); JPanel jPanel2 = new JPanel(); JScrollPane jScrollPane1 = new JScrollPane(); JLabel jLabel1 = new JLabel(); JTextField orderIdTxt = new JTextField(); JLabel jLabel2 = new JLabel(); JLabel jLabel3 = new JLabel(); JLabel jLabel4 = new JLabel(); JLabel jLabel5 = new JLabel(); JTextField custIdTxt = new JTextField(); JTextField custNameTxt = new JTextField(); JTextField custAddressTxt = new JTextField(); JTextField custPhoneTxt = new JTextField(); JButton findBtn = new JButton(); JLabel jLabel6 = new JLabel(); JTextField prodIdTxt = new JTextField(); JButton addBtn = new JButton(); JButton removeBtn = new JButton(); JLabel jLabel7 = new JLabel(); Order Entry Solution Oracle 10g: Java Programming C-20

21 Oracle 10g: Java Programming C-21
OrderEntryFrame.java (continued) JLabel orderDateLbl = new JLabel(); JLabel jLabel8 = new JLabel(); JLabel orderTotalLbl = new JLabel(); JList orderItemList = new JList(); Order order = null; private static int x = 0; private static int y = 0; private static final int OFFSET = 20; private static final int MAX_OFFSET = 200; JLabel taxTextLbl = new JLabel(); JLabel totalTaxLbl = new JLabel(); public OrderEntryFrame() { try jbInit(); } catch(Exception e) e.printStackTrace(); private void jbInit() throws Exception this.setTitle("Order"); this.setBounds(0, 0, 400, 300); this.setMaximizable(true); this.setIconifiable(true); this.setClosable(true); this.getContentPane().setLayout(borderLayout1); jPanel1.setLayout(gridLayout1); gridLayout1.setColumns(1); gridLayout1.setRows(2); Order Entry Solution Oracle 10g: Java Programming C-21

22 Oracle 10g: Java Programming C-22
OrderEntryFrame.java (continued) jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); jPanel2.setLayout(null); jLabel1.setText("Order Id"); jLabel1.setBounds(new Rectangle(5, 5, 59, 16)); orderIdTxt.setBounds(new Rectangle(75, 5, 59, 20)); jLabel2.setText("Customer Id"); jLabel2.setBounds(new Rectangle(3, 28, 71, 16)); jLabel3.setText("Name"); jLabel3.setBounds(new Rectangle(5, 50, 57, 16)); jLabel4.setText("Address"); jLabel4.setBounds(new Rectangle(5, 70, 59, 16)); jLabel5.setText("Phone"); jLabel5.setBounds(new Rectangle(5, 90, 34, 16)); custIdTxt.setBounds(new Rectangle(75, 30, 59, 20)); custNameTxt.setBounds(new Rectangle(75, 50, 140, 20)); custAddressTxt.setBounds(new Rectangle(75, 70, 140, 20)); custPhoneTxt.setBounds(new Rectangle(75, 90, 140, 20)); findBtn.setText("Find"); findBtn.setBounds(new Rectangle(137, 27, 73, 21)); findBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) findBtn_actionPerformed(e); } }); jLabel6.setText("Product Id"); jLabel6.setBounds(new Rectangle(230, 70, 59, 16)); prodIdTxt.setBounds(new Rectangle(295, 68, 85, 20)); addBtn.setText("Add"); addBtn.setBounds(new Rectangle(230, 90, 55, 23)); addBtn.addActionListener(new ActionListener() addBtn_actionPerformed(e); Order Entry Solution Oracle 10g: Java Programming C-22

23 Oracle 10g: Java Programming C-23
OrderEntryFrame.java (continued) removeBtn.setEnabled(false); removeBtn.setText("Remove"); removeBtn.setBounds(new Rectangle(295, 90, 85, 23)); removeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) removeBtn_actionPerformed(e); } }); jLabel7.setText("Order Date"); jLabel7.setBounds(new Rectangle(230, 5, 63, 16)); orderDateLbl.setBorder(BorderFactory.createLineBorder(Color.black, 1)); orderDateLbl.setBounds(new Rectangle(295, 5, 85, 16)); jLabel8.setText("Order Total"); jLabel8.setBounds(new Rectangle(230, 25, 61, 16)); orderTotalLbl.setBorder(BorderFactory.createLineBorder(Color.black, 1)); orderTotalLbl.setBounds(new Rectangle(295, 25, 85, 16)); orderItemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); orderItemList.addListSelectionListener(new ListSelectionListener() public void valueChanged(ListSelectionEvent e) orderItemList_valueChanged(e); taxTextLbl.setText("Total Tax"); taxTextLbl.setBounds(new Rectangle(230, 45, 65, 16)); Order Entry Solution Oracle 10g: Java Programming C-23

24 Oracle 10g: Java Programming C-24
OrderEntryFrame.java (continued) totalTaxLbl.setBorder(BorderFactory.createLineBorder(Color.black, 1)); totalTaxLbl.setBounds(new Rectangle(295, 45, 85, 16)); jPanel2.add(totalTaxLbl, null); jPanel2.add(taxTextLbl, null); jPanel2.add(orderTotalLbl, null); jPanel2.add(jLabel8, null); jPanel2.add(orderDateLbl, null); jPanel2.add(jLabel7, null); jPanel2.add(removeBtn, null); jPanel2.add(addBtn, null); jPanel2.add(prodIdTxt, null); jPanel2.add(jLabel6, null); jPanel2.add(findBtn, null); jPanel2.add(custPhoneTxt, null); jPanel2.add(custAddressTxt, null); jPanel2.add(custNameTxt, null); jPanel2.add(custIdTxt, null); jPanel2.add(jLabel5, null); jPanel2.add(jLabel4, null); jPanel2.add(jLabel3, null); jPanel2.add(jLabel2, null); jPanel2.add(orderIdTxt, null); jPanel2.add(jLabel1, null); jPanel1.add(jPanel2, null); jScrollPane1.getViewport().add(orderItemList, null); jPanel1.add(jScrollPane1, null); this.getContentPane().add(jPanel1, BorderLayout.CENTER); initOrder(); setBounds(); taxTextLbl.setVisible(false); totalTaxLbl.setVisible(false); } Order Entry Solution Oracle 10g: Java Programming C-24

25 Oracle 10g: Java Programming C-25
OrderEntryFrame.java (continued) private void initOrder() { order = new Order(); orderIdTxt.setText(Integer.toString(order.getId())); orderDateLbl.setText(Util.toDateString(order.getOrderDate())); orderTotalLbl.setText(Util.toMoney(order.getOrderTotal())); } private void setBounds() this.setResizable(true); this.setBounds(x, y, this.getWidth(), this.getHeight()); x = (x + OFFSET) % MAX_OFFSET; y = (y + OFFSET) % MAX_OFFSET; public void setActive(boolean active) try this.setSelected(active); catch (Exception e) {} this.setVisible(active); if (active) this.toFront(); void findBtn_actionPerformed(ActionEvent e) int custId = 0; Customer customer = null; Order Entry Solution Oracle 10g: Java Programming C-25

26 Oracle 10g: Java Programming C-26
OrderEntryFrame.java (continued) if (custIdTxt.getText().length() > 0) { try custId = Integer.parseInt(custIdTxt.getText()); customer = DataMan.findCustomerById(custId); order.setCustomer(customer); custNameTxt.setText(customer.getName()); custAddressTxt.setText(customer.getAddress()); custPhoneTxt.setText(customer.getPhone()); } catch (NumberFormatException err) JOptionPane.showMessageDialog(this, "The Customer Id: " + err.getMessage() + " is not a valid number", "Error", JOptionPane.ERROR_MESSAGE); custIdTxt.setText(""); catch (NotFoundException err) JOptionPane.showMessageDialog(this, err.getMessage(), } else JOptionPane.showMessageDialog(this, "Please enter a Customer Id", "Error", JOptionPane.ERROR_MESSAGE); void addBtn_actionPerformed(ActionEvent e) Product p = null; int prodId = 0; Order Entry Solution Oracle 10g: Java Programming C-26

27 Oracle 10g: Java Programming C-27
OrderEntryFrame.java (continued) if (prodIdTxt.getText().length() > 0) { try prodId = Integer.parseInt(prodIdTxt.getText()); p = DataMan.findProductById(prodId); order.addOrderItem(prodId); if (orderItemList.getModel().getSize() == 0) orderItemList.setModel(order.getModel()); } orderItemList.updateUI(); orderTotalLbl.setText(Util.toMoney(order.getOrderTotal())); showTaxFields(); catch (Exception err) String message = err.getMessage(); if (err instanceof NumberFormatException) message = "Product Id '" + message + "' is not a valid number"; JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE); prodIdTxt.setText(""); } else JOptionPane.showMessageDialog(this, "Please enter a Product Id", "Error", JOptionPane.ERROR_MESSAGE); Order Entry Solution Oracle 10g: Java Programming C-27

28 Oracle 10g: Java Programming C-28
OrderEntryFrame.java (continued) void orderItemList_valueChanged(ListSelectionEvent e) { if (orderItemList.isSelectionEmpty()) removeBtn.setEnabled(false); } else removeBtn.setEnabled(true); } void removeBtn_actionPerformed(ActionEvent e) OrderItem item = (OrderItem) orderItemList.getSelectedValue(); order.removeOrderItem(item.getProduct().getId()); orderItemList.updateUI(); orderTotalLbl.setText(Util.toMoney(order.getOrderTotal())); showTaxFields(); private void showTaxFields() if (order.getTax() > 0.0) totalTaxLbl.setText(Util.toMoney(order.getTax())); orderTotalLbl.setText(Util.toMoney(order.getTax() + order.getOrderTotal())); taxTextLbl.setVisible(true); totalTaxLbl.setVisible(true); else taxTextLbl.setVisible(false); totalTaxLbl.setVisible(false); Order Entry Solution Oracle 10g: Java Programming C-28

29 Oracle 10g: Java Programming C-29
OrderEntryMDIFrame.java package oe; import javax.swing.JFrame; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JDesktopPane; public class OrderEntryMDIFrame extends JFrame { JLabel statusBar = new JLabel(); JMenuItem menuFileExit = new JMenuItem(); JMenu menuFile = new JMenu(); JMenuBar menuBar1 = new JMenuBar(); JDesktopPane desktopPane = new JDesktopPane(); BorderLayout borderLayout1 = new BorderLayout(); JMenu menuOrder = new JMenu(); JMenuItem newMenuItem = new JMenuItem(); JMenuItem openMenuItem = new JMenuItem(); JMenuItem saveMenuItem = new JMenuItem(); JMenuItem closeMenuItem = new JMenuItem(); JMenuItem printMenuItem = new JMenuItem(); public OrderEntryMDIFrame() try jbInit(); } catch(Exception e) e.printStackTrace(); Order Entry Solution Oracle 10g: Java Programming C-29

30 Oracle 10g: Java Programming C-30
OrderEntryMDIFrame.java (continued) private void jbInit() throws Exception { this.setJMenuBar(menuBar1); this.getContentPane().setLayout(borderLayout1); desktopPane.setLayout(null); menuOrder.setText("Order"); newMenuItem.setText("New"); newMenuItem.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) newMenuItem_actionPerformed(e); } }); openMenuItem.setText("Open"); saveMenuItem.setText("Save"); closeMenuItem.setText("Close"); printMenuItem.setText("Print"); this.setSize(new Dimension(700, 500)); this.setTitle("Order Entry Application"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener(new ActionListener() public void actionPerformed(ActionEvent ae) fileExit_ActionPerformed(ae); statusBar.setText(""); menuFile.add(menuFileExit); menuBar1.add(menuFile); menuOrder.add(newMenuItem); menuOrder.add(openMenuItem); menuOrder.add(saveMenuItem); menuOrder.add(closeMenuItem); menuOrder.addSeparator(); menuOrder.add(printMenuItem); menuBar1.add(menuOrder); this.getContentPane().add(statusBar, BorderLayout.SOUTH); this.getContentPane().add(desktopPane, BorderLayout.CENTER); Order Entry Solution Oracle 10g: Java Programming C-30

31 Oracle 10g: Java Programming C-31
OrderEntryMDIFrame.java (continued) void fileExit_ActionPerformed(ActionEvent e) { System.exit(0); } void newMenuItem_actionPerformed(ActionEvent e) OrderEntryFrame iFrame = new OrderEntryFrame(); //iFrame.setVisible(true); desktopPane.add(iFrame); iFrame.setActive(true); Order Entry Solution Oracle 10g: Java Programming C-31

32 Oracle 10g: Java Programming C-32
OrderItem.java package oe; public class OrderItem { private int lineNbr; private int quantity; private double unitPrice; private Product product; public OrderItem(Product newProduct) product = newProduct; unitPrice = product.getRetailPrice(); quantity = 1; } public int getLineNbr() return lineNbr; public int getQuantity() return quantity; public double getUnitPrice() return unitPrice; public Product getProduct() return product; public double getItemTotal() return quantity * unitPrice; public void setLineNbr(int newLineNbr) lineNbr = newLineNbr; Order Entry Solution Oracle 10g: Java Programming C-32

33 Oracle 10g: Java Programming C-33
OrderItem.java (continued) public void setQuantity(int newQuantity) { quantity = newQuantity; } public void setUnitPrice(double newUnitPrice) unitPrice = newUnitPrice; public void setProduct(Product newProduct) product = newProduct; public double getTax() double itemTax = 0.0; if (product instanceof Taxable) itemTax =((Taxable) product).getTax(getItemTotal()); return itemTax; public String toString() String result = lineNbr + " product: " + product + " qty: " + quantity; result += " tax: " + Util.toMoney(getTax()); result += " Item total: " + Util.toMoney(getItemTotal()); return result; Order Entry Solution Oracle 10g: Java Programming C-33

34 Oracle 10g: Java Programming C-34
Product.java package oe; public abstract class Product { private static int nextProductId = 2000; private int id; private String name; private String description; private double retailPrice; public Product() id = nextProductId++; } public int getId() return id; public void setId(int newId) id = newId; public String getName() return name; public void setName(String newName) name = newName; public String getDescription() return description; public void setDescription(String newDescription) description = newDescription; Order Entry Solution Oracle 10g: Java Programming C-34

35 Oracle 10g: Java Programming C-35
Product.java (continued) public double getRetailPrice() { return retailPrice; } public void setRetailPrice(double newRetailPrice) retailPrice = newRetailPrice; public String toString() return "[" + Util.getClassName(this) + "] " + id + " " + name + " " + Util.toMoney(retailPrice); Order Entry Solution Oracle 10g: Java Programming C-35

36 Oracle 10g: Java Programming C-36
Software.java package oe; public class Software extends Product { private String license = "30 Day Trial"; public Software(String name, String desc, double price) setName(name); setDescription(desc); setRetailPrice(price); } public String getLicense() return license; public void setLicense(String newLicense) license = newLicense; Order Entry Solution Oracle 10g: Java Programming C-36

37 Oracle 10g: Java Programming C-37
Taxable.java package oe; public interface Taxable { double TAX_RATE = 0.10; double getTax(double amount); } Order Entry Solution Oracle 10g: Java Programming C-37

38 Oracle 10g: Java Programming C-38
Util.java package oe; import java.text.DecimalFormat; import java.util.Date; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; public class Util { public static boolean isLeapYear(int year) return (year % 4 == 0) && ((year% 100 != 0) || (year % 400 == 0)); } public static int lastDayInMonth(int month, int year) int daysInMonth = 0; switch (month) case 1: case 3: case 5: case 7: case 8: case 10: case 12: daysInMonth = 31; break; case 2: daysInMonth = isLeapYear(year) ? 29 : 28; case 4: case 6: case 9: case 11: daysInMonth = 30; return daysInMonth; Order Entry Solution Oracle 10g: Java Programming C-38

39 Oracle 10g: Java Programming C-39
Util.java (continued) public static int getDaysToShip(char region) { int daysToShip = 1; switch (region) case 'A': daysToShip = 3; break; case 'E': daysToShip = 5; case 'P': daysToShip = 7; } return daysToShip; public static void main(String[] args) int year = 1900; System.out.println("Year: " + year + " leap year? " + isLeapYear(year)); year = 1964; year = 1967; year = 1984; year = 1996; year = 1997; year = 2000; System.out.println("Year: " + year + " leap year? " + Order Entry Solution Oracle 10g: Java Programming C-39

40 Oracle 10g: Java Programming C-40
Util.java (continued) isLeapYear(year)); year = 2001; System.out.println("Year: " + year + " leap year? " + isLeapYear(year)); int day = 27; int month = 1; year = 2002; int daysInMonth = lastDayInMonth(month, year); System.out.println("Date is: " + day + "/" + month + "/" + year + " (and has " + daysInMonth + " days in the month)"); day = 20; month = 2; year = 2000; daysInMonth = lastDayInMonth(month, year); /* ** Remove comments to test with month 13. ** month = 13; */ int daysToShip = getDaysToShip('A'); System.out.println("It takes " + daysToShip + " days to ship to Americas"); day = 27; month = 1; Order Entry Solution Oracle 10g: Java Programming C-40

41 Oracle 10g: Java Programming C-41
Util.java (continued) /* ** Solution to 4b. for (int aDay = day; aDay <= daysInMonth; aDay++) { System.out.println(aDay + "/" + month + "/" + year); } */ day = 10; month = 2; ** 4e. with 'E' or 'P' daysToShip = getDaysToShip('E'); daysToShip = getDaysToShip('P'); for (int aDay = day, j = 0; aDay <= daysInMonth && j < daysToShip; aDay++, j++) public static String toMoney(double amount) DecimalFormat df = new DecimalFormat("$##,###.00"); return df.format(amount); public static String toDateString(Date d) SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy"); return df.format(d); public static Date getDate(int day, int month, int year) GregorianCalendar gc = new GregorianCalendar(year, --month, day); return gc.getTime(); public static String getClassName(Object o) String className = o.getClass().getName(); return className.substring(className.lastIndexOf('.')+1, className.length()); Order Entry Solution Oracle 10g: Java Programming C-41

42 Oracle 10g: Java Programming C-42
OrderEntryWS.jnlp <?xml version = '1.0' encoding = 'windows-1252'?> <jnlp spec="1.0+" codebase="http://localhost:8888" href="/OrderEntryWorkspaceLesWS-Project1-context-root/OrderEntryWS.jnlp"> <information> <title>Order Entry WebStart Application</title> <vendor>Curriculum Development</vendor> <homepage href="OrderEntryWS.html"/> <description>Oracel Java Programming course</description> <offline-allowed/> </information> <resources> <j2se version="1.4+"/> <jar href="/OrderEntryWorkspaceLesWS-Project1-context-root/apps/archive1.jar" main="true" download="eager"/> </resources> <application-desc main-class="oe.OrderEntry"/> </jnlp> Order Entry Solution Oracle 10g: Java Programming C-42

43 Oracle 10g: Java Programming C-43
OrderEntryWS.html <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"></META> <TITLE>Title</TITLE> <SCRIPT LANGUAGE="Javascript"> var javawsInstalled = 0; isIE = "false"; if (navigator.mimeTypes && navigator.mimeTypes.length) { x = navigator.mimeTypes['application/x-java-jnlp-file']; if (x) javawsInstalled = 1; } else isIE = "true"; function insertLink(url, name) if (javawsInstalled) document.write("<a href=" + url + ">" + name + "</a>"); document.write("Need to install Java Web Start"); </SCRIPT> <SCRIPT LANGUAGE="VBScript"> on error resume next If isIE = "true" Then If Not(IsObject(CreateObject("JavaWebStart.IsInstalled"))) Then javawsInstalled = 0 Else javawsInstalled = 1 End If Order Entry Solution Oracle 10g: Java Programming C-43

44 Oracle 10g: Java Programming C-44
OrderEntryWS.html (continued) If Not(IsObject(CreateObject("JavaWebStart.isInstalled.2"))) Then javaws12Installed = 0 Else javaws12Installed = 1 End If If Not(IsObject(CreateObject("JavaWebStart.isInstalled "))) Then javaws142Installed = 0 javaws142Installed = 1 </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> insertLink("OrderEntryWS.jnlp", "Click here to start your Web Start Application") </BODY> </HTML> Order Entry Solution Oracle 10g: Java Programming C-44

45 Oracle 10g: Java Programming C-45
Web.xml <?xml version = '1.0' encoding = 'windows-1252'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>Empty web.xml file for Web Application</description> <session-config> <session-timeout>35</session-timeout> </session-config> <mime-mapping> <extension>html</extension> <mime-type>text/html</mime-type> </mime-mapping> <extension>txt</extension> <mime-type>text/plain</mime-type> <extension>jnlp</extension> <mime-type>application/x-java-jnlp-file</mime-type> </web-app> Order Entry Solution Oracle 10g: Java Programming C-45

46


Download ppt "Practice Solutions."

Similar presentations


Ads by Google