001package horstmann.ch05_invoice;
002import java.awt.BorderLayout;
003import javax.swing.JButton;
004import javax.swing.JComboBox;
005import javax.swing.JFrame;
006import javax.swing.JPanel;
007import javax.swing.JScrollPane;
008import javax.swing.JTextArea;
009import javax.swing.event.ChangeListener;
010
011/**
012   A program that tests the invoice classes.
013 */
014public class InvoiceTester
015{
016        public static void main(String[] args)
017        {
018                final Invoice invoice = new Invoice();
019                final InvoiceFormatter formatter = new SimpleFormatter();
020
021                // This text area will contain the formatted invoice
022                final JTextArea textArea = new JTextArea(20, 40);
023
024                // When the invoice changes, update the text area
025                ChangeListener listener = event -> textArea.setText(invoice.format(formatter));
026                invoice.addChangeListener(listener);
027
028                // Add line items to a combo box
029                final JComboBox<LineItem> combo = new JComboBox<>();
030                Product hammer = new Product("Hammer", 19.95);
031                Product nails = new Product("Assorted nails", 9.95);
032                combo.addItem(hammer);
033                Bundle bundle = new Bundle();
034                bundle.add(hammer);
035                bundle.add(nails);
036                combo.addItem(new DiscountedItem(bundle, 10));
037
038                // Make a button for adding the currently selected
039                // item to the invoice
040                JButton addButton = new JButton("Add");
041                addButton.addActionListener(event -> {
042                        LineItem item = (LineItem) combo.getSelectedItem();
043                        invoice.addItem(item);
044                });
045
046                // Put the combo box and the add button into a panel
047                JPanel panel = new JPanel();
048                panel.add(combo);
049                panel.add(addButton);
050
051                // Add the text area and panel to the content pane
052                JFrame frame = new JFrame();
053                frame.add(new JScrollPane(textArea),
054                                BorderLayout.CENTER);
055                frame.add(panel, BorderLayout.SOUTH);
056                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
057                frame.pack();
058                frame.setVisible(true);
059        }
060}