// Stuart Reges // 1/19/00 // // Class ShoppingFrame provides the user interface for a simple shopping // program. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.*; public class ShoppingFrame extends JFrame { private final ShoppingCart myItems; private final JTextField myTotal; public ShoppingFrame(Catalog products) { // create frame and order list setTitle(products.getName()); setDefaultCloseOperation(EXIT_ON_CLOSE); Container contentPane = getContentPane(); myItems = new ShoppingCart(); // set up text field with order total myTotal = new JTextField("$0.00", 12); myTotal.setEditable(false); myTotal.setEnabled(false); myTotal.setDisabledTextColor(Color.black); JPanel p = new JPanel(); p.setBackground(Color.blue); JLabel l = new JLabel("order total"); l.setForeground(Color.yellow); p.add(l); p.add(myTotal); contentPane.add(p, "North"); p = new JPanel(new GridLayout(products.length(), 1)); for (int i = 0; i < products.length(); i++) addItem(products.get(i), p); contentPane.add(p, "Center"); p = new JPanel(); contentPane.add(makeCheckBoxPanel(), "South"); // adjust size to just fit pack(); } private JPanel makeCheckBoxPanel() { JPanel p = new JPanel(); p.setBackground(Color.blue); final JCheckBox cb = new JCheckBox("qualify for discount"); p.add(cb); cb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myItems.setDiscount(cb.isSelected()); updateTotal(); } }); return p; } private void addItem(final Item product, JPanel p) { JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT)); sub.setBackground(new Color(0, 180, 0)); final JTextField quantity = new JTextField(3); quantity.setHorizontalAlignment(SwingConstants.CENTER); quantity.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateItem(product, quantity); quantity.transferFocus(); } }); quantity.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { updateItem(product, quantity); } }); sub.add(quantity); JLabel l = new JLabel("" + product); l.setForeground(Color.white); sub.add(l); p.add(sub); } private void updateItem(Item product, JTextField quantity) { int number; String text = quantity.getText().trim(); try { number = Integer.parseInt(text); } catch (NumberFormatException error) { number = 0; } myItems.add(new ItemOrder(product, number)); updateTotal(); } private void updateTotal() { double total = myItems.getTotal(); myTotal.setText(NumberFormat.getCurrencyInstance().format(total)); } }