01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
package horstmann.ch05_invoice;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeListener;
/**
A program that tests the invoice classes.
*/
public class InvoiceTester
{
public static void main(String[] args)
{
final Invoice invoice = new Invoice();
final InvoiceFormatter formatter = new SimpleFormatter();
// This text area will contain the formatted invoice
final JTextArea textArea = new JTextArea(20, 40);
// When the invoice changes, update the text area
ChangeListener listener = event -> textArea.setText(invoice.format(formatter));
invoice.addChangeListener(listener);
// Add line items to a combo box
final JComboBox<LineItem> combo = new JComboBox<>();
Product hammer = new Product("Hammer", 19.95);
Product nails = new Product("Assorted nails", 9.95);
combo.addItem(hammer);
Bundle bundle = new Bundle();
bundle.add(hammer);
bundle.add(nails);
combo.addItem(new DiscountedItem(bundle, 10));
// Make a button for adding the currently selected
// item to the invoice
JButton addButton = new JButton("Add");
addButton.addActionListener(event -> {
LineItem item = (LineItem) combo.getSelectedItem();
invoice.addItem(item);
});
// Put the combo box and the add button into a panel
JPanel panel = new JPanel();
panel.add(combo);
panel.add(addButton);
// Add the text area and panel to the content pane
JFrame frame = new JFrame();
frame.add(new JScrollPane(textArea),
BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
|