1 package org.uncommons.watchmaker.examples.travellingsalesman;
17
18 import java.awt.BorderLayout;
19 import java.awt.GridLayout;
20 import java.awt.event.ActionEvent;
21 import java.awt.event.ActionListener;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.TreeSet;
27 import javax.swing.BorderFactory;
28 import javax.swing.JButton;
29 import javax.swing.JCheckBox;
30 import javax.swing.JPanel;
31
32
37 final class ItineraryPanel extends JPanel
38 {
39 private final Collection<JCheckBox> checkBoxes;
40 private JButton selectAllButton;
41 private JButton clearButton;
42
43 public ItineraryPanel(List<String> cities)
44 {
45 super(new BorderLayout());
46
47 JPanel checkBoxPanel = new JPanel(new GridLayout(0, 1));
48 checkBoxes = new ArrayList<JCheckBox>(cities.size());
49 for (String city : cities)
50 {
51 JCheckBox checkBox = new JCheckBox(city, false);
52 checkBox.setName(city); checkBoxes.add(checkBox);
54 checkBoxPanel.add(checkBox);
55 }
56 add(checkBoxPanel, BorderLayout.CENTER);
57
58 JPanel buttonPanel = new JPanel(new GridLayout(2, 1));
59 selectAllButton = new JButton("Select All");
60 selectAllButton.setName("All");
61 buttonPanel.add(selectAllButton);
62 clearButton = new JButton("Clear Selection");
63 clearButton.setName("None");
64 buttonPanel.add(clearButton);
65 ActionListener buttonListener = new ActionListener()
66 {
67
68 public void actionPerformed(ActionEvent actionEvent)
69 {
70 boolean select = actionEvent.getSource() == selectAllButton;
71 for (JCheckBox checkBox : checkBoxes)
72 {
73 checkBox.setSelected(select);
74 }
75 }
76 };
77 selectAllButton.addActionListener(buttonListener);
78 clearButton.addActionListener(buttonListener);
79 add(buttonPanel, BorderLayout.SOUTH);
80
81 setBorder(BorderFactory.createTitledBorder("Itinerary"));
82 }
83
84
85
88 public Collection<String> getSelectedCities()
89 {
90 Set<String> cities = new TreeSet<String>();
91 for (JCheckBox checkBox : checkBoxes)
92 {
93 if (checkBox.isSelected())
94 {
95 cities.add(checkBox.getText());
96 }
97 }
98 return cities;
99 }
100
101
102 @Override
103 public void setEnabled(boolean b)
104 {
105 for (JCheckBox checkBox : checkBoxes)
106 {
107 checkBox.setEnabled(b);
108 }
109 selectAllButton.setEnabled(b);
110 clearButton.setEnabled(b);
111 super.setEnabled(b);
112 }
113 }
114