001
002 /*****************************************************************************
003
004 jBudget.
005 Copyright (C) 2006 Dmitri Petrov
006
007 This program is free software: you can redistribute it and/or modify
008 it under the terms of the GNU General Public License as published by
009 the Free Software Foundation, either version 3 of the License, or
010 (at your option) any later version.
011
012 This program is distributed in the hope that it will be useful,
013 but WITHOUT ANY WARRANTY; without even the implied warranty of
014 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 GNU General Public License for more details.
016
017 You should have received a copy of the GNU General Public License
018 along with this program. If not, see <http://www.gnu.org/licenses/>.
019
020 /*****************************************************************************
021
022 /*
023 * MonthSelectorPanel.java
024 *
025 * Created on June 1, 2006, 4:41 PM
026 */
027
028 package org.jbudget.gui.month;
029
030 import java.awt.Dimension;
031 import java.awt.FontMetrics;
032 import java.awt.event.ActionEvent;
033 import java.awt.event.ActionListener;
034 import java.util.ArrayList;
035 import java.util.Calendar;
036 import java.util.Collection;
037 import java.util.Collections;
038 import java.util.HashMap;
039 import java.util.HashSet;
040 import java.util.LinkedList;
041 import java.util.List;
042 import java.util.Map;
043 import java.util.Set;
044 import javax.swing.JToggleButton;
045 import org.jbudget.gui.templ.MonthSelectorTemplate;
046 import org.jbudget.io.DataManager;
047 import org.jbudget.util.DateFormater;
048
049 /**
050 * A GUI widget for choosing months.
051 * @author petrov
052 */
053 public class MonthSelectorPanel extends MonthSelectorTemplate
054 {
055 /** If true, only valid months can be selected. Otherwise, only inactive
056 * months can be selected.
057 */
058 private final boolean activateValidMonths;
059
060 Calendar calendar = Calendar.getInstance();
061 int cYear = calendar.get(Calendar.YEAR);
062 int cMonth = calendar.get(Calendar.MONTH);
063
064 /** A list of components listening for month selections */
065 List<SelectionListener> listeners = new LinkedList<SelectionListener>();
066
067 /** A Map of month indices to buttons */
068 private final Map<Integer, JToggleButton> monthToButtonMap =
069 new HashMap<Integer, JToggleButton>();
070
071 /** A Map of Buttons to month indices */
072 private final Map<JToggleButton, Integer> buttonToMonthMap =
073 new HashMap<JToggleButton, Integer>();
074
075 /** A Map of selected months. */
076 private final Map<Integer, Set<Integer>> selectedMonthsMap =
077 new HashMap<Integer, Set<Integer>>();
078
079 /** If true, only one month can be selected. */
080 private boolean exclusive = false;
081
082 // ========================================================================
083 //
084 // Methods.
085 //
086 // ========================================================================
087
088 //=================== Constructors and Initializers =====================//
089
090 /** Creates a new instance of MonthSelectorPanel */
091 public MonthSelectorPanel(boolean activateValidMonths)
092 {
093 super();
094 this.activateValidMonths = activateValidMonths;
095
096 monthToButtonMap.put(new Integer(Calendar.JANUARY), januaryButton);
097 buttonToMonthMap.put(januaryButton, new Integer(Calendar.JANUARY));
098 monthToButtonMap.put(new Integer(Calendar.FEBRUARY), februaryButton);
099 buttonToMonthMap.put(februaryButton, new Integer(Calendar.FEBRUARY));
100 monthToButtonMap.put(new Integer(Calendar.MARCH), marchButton);
101 buttonToMonthMap.put(marchButton, new Integer(Calendar.MARCH));
102 monthToButtonMap.put(new Integer(Calendar.APRIL), aprilButton);
103 buttonToMonthMap.put(aprilButton, new Integer(Calendar.APRIL));
104 monthToButtonMap.put(new Integer(Calendar.MAY), mayButton);
105 buttonToMonthMap.put(mayButton, new Integer(Calendar.MAY));
106 monthToButtonMap.put(new Integer(Calendar.JUNE), juneButton);
107 buttonToMonthMap.put(juneButton, new Integer(Calendar.JUNE));
108 monthToButtonMap.put(new Integer(Calendar.JULY), julyButton);
109 buttonToMonthMap.put(julyButton, new Integer(Calendar.JULY));
110 monthToButtonMap.put(new Integer(Calendar.AUGUST), augustButton);
111 buttonToMonthMap.put(augustButton, new Integer(Calendar.AUGUST));
112 monthToButtonMap.put(new Integer(Calendar.SEPTEMBER), septemberButton);
113 buttonToMonthMap.put(septemberButton, new Integer(Calendar.SEPTEMBER));
114 monthToButtonMap.put(new Integer(Calendar.OCTOBER), octoberButton);
115 buttonToMonthMap.put(octoberButton, new Integer(Calendar.OCTOBER));
116 monthToButtonMap.put(new Integer(Calendar.NOVEMBER), novemberButton);
117 buttonToMonthMap.put(novemberButton, new Integer(Calendar.NOVEMBER));
118 monthToButtonMap.put(new Integer(Calendar.DECEMBER), decemberButton);
119 buttonToMonthMap.put(decemberButton, new Integer(Calendar.DECEMBER));
120
121 updateGui();
122 initializeActions();
123 updateSizes();
124 }
125
126 /** synchronizes the widget with the internal state.
127 * Called whenever the value of cYear is changed. */
128 private void updateGui()
129 {
130 yearTextField.setText(Integer.toString(cYear));
131 DataManager dataManager = DataManager.getInstance();
132
133 Integer iYear = new Integer(cYear);
134 List<Integer> validMonths;
135 if (dataManager.getValidYears().contains(iYear))
136 validMonths = dataManager.getValidMonths(cYear);
137 else
138 validMonths = Collections.emptyList();
139
140 Set<Integer> selectedMonths;
141 if (selectedMonthsMap.keySet().contains(iYear))
142 selectedMonths = selectedMonthsMap.get(iYear);
143 else
144 selectedMonths = Collections.emptySet();
145
146 for (int month = Calendar.JANUARY;
147 month <= Calendar.DECEMBER; month++)
148 {
149 JToggleButton monthButton = monthToButtonMap.get(new Integer(month));
150 assert monthButton != null : "No button for month " + month;
151 monthButton.setEnabled(
152 (activateValidMonths && dataManager.isValidMonth(month, cYear)) ||
153 (!activateValidMonths) && (!dataManager.isValidMonth(month, cYear)));
154
155 monthButton.setSelected(selectedMonths.contains(new Integer(month)));
156 }
157 }
158
159 /** Initializes actions associated with buttons.
160 * Called once from the constructor. */
161 private void initializeActions()
162 {
163 prevYearButton.addActionListener(new ActionListener()
164 {
165 public void actionPerformed(ActionEvent ev)
166 {
167 cYear--;
168 updateGui();
169 notifyYearChanged();
170 }
171 });
172
173 nextYearButton.addActionListener(new ActionListener()
174 {
175 public void actionPerformed(ActionEvent ev)
176 {
177 cYear++;
178 updateGui();
179 notifyYearChanged();
180 }
181 });
182
183 yearTextField.addActionListener(new ActionListener()
184 {
185 public void actionPerformed(ActionEvent ev)
186 {
187 try
188 {
189 cYear = Integer.parseInt(yearTextField.getText());
190 }
191 catch (NumberFormatException ex)
192 {
193 }
194 updateGui();
195 }
196 });
197
198 ActionListener monthActionListener = new ActionListener()
199 {
200 public void actionPerformed(ActionEvent ev)
201 {
202 String command = ev.getActionCommand();
203 JToggleButton button = (JToggleButton) ev.getSource();
204 try
205 {
206 cMonth = (new DateFormater()).parseMonth(command);
207 Integer iYear = new Integer(cYear);
208 Integer iMonth = new Integer(cMonth);
209 if (button.isSelected())
210 {
211 //If in exclusive mode, deselect all other months.
212 if (exclusive)
213 selectedMonthsMap.clear();
214
215 Set<Integer> selectedMonths = selectedMonthsMap.get(iYear);
216 if (selectedMonths == null)
217 {
218 selectedMonths = new HashSet<Integer>();
219 selectedMonthsMap.put(iYear, selectedMonths);
220 }
221 selectedMonths.add(iMonth);
222 if (exclusive)
223 updateGui();
224 notifyListenersSelected();
225 }
226 else
227 {
228 // Prevent users from deselecting months in the exclusive mode.
229 if (exclusive)
230 {
231 updateGui();
232 return;
233 }
234
235 Set<Integer> selectedMonths = selectedMonthsMap.get(iYear);
236 if (selectedMonths != null)
237 selectedMonths.remove(iMonth);
238 notifyListenersDeselected();
239 }
240 }
241 catch (Exception ex)
242 {
243 throw new RuntimeException(ex);
244 }
245 }
246 };
247
248 Collection<JToggleButton> buttons = monthToButtonMap.values();
249 for (JToggleButton button : buttons)
250 button.addActionListener(monthActionListener);
251 }
252
253 /** sets the preferred component sizes. */
254 protected void updateSizes()
255 {
256 if (buttonToMonthMap == null)
257 return;
258
259 // Set the size of the 'Year:' label
260 FontMetrics metrics = getFontMetrics(yearLabel.getFont());
261 int width = metrics.stringWidth(yearLabel.getText());
262 int height = metrics.getHeight();
263 yearLabel.setPreferredSize(new Dimension((int) (width * 1.2), height));
264
265 // Set the preferred size of the month buttons.
266 int maxWidth = 0;
267 int maxHeight = 0;
268 for (JToggleButton button : buttonToMonthMap.keySet())
269 {
270 String monthName = button.getText();
271 metrics = getFontMetrics(button.getFont());
272
273 width = metrics.stringWidth(monthName);
274 height = metrics.getHeight();
275
276 if (width > maxWidth)
277 maxWidth = width;
278 if (height > maxHeight)
279 maxHeight = height;
280 }
281
282 Dimension prefSize = new Dimension((int) (maxWidth + 10), (int) (maxHeight + 4));
283 for (JToggleButton button : buttonToMonthMap.keySet())
284 button.setPreferredSize(prefSize);
285
286 this.setPreferredSize(new Dimension((int) (maxWidth * 4), (int) (maxHeight * 10)));
287 }
288
289 @Override
290 public void updateUI()
291 {
292 super.updateUI();
293 updateSizes();
294 }
295
296
297 //============================== Accessors ===============================//
298
299 /** Retruns a map that provides a set of selected months for every year. */
300 public Map<Integer, Set<Integer>> getSelectedMonths()
301 {
302 return Collections.unmodifiableMap(selectedMonthsMap);
303 }
304
305 /** Enable/Disable this component. */
306 @Override
307 public void setEnabled(boolean enabled)
308 {
309 Collection<JToggleButton> buttons = monthToButtonMap.values();
310 for (JToggleButton button : buttons)
311 button.setEnabled(enabled);
312
313 prevYearButton.setEnabled(enabled);
314 nextYearButton.setEnabled(enabled);
315 yearTextField.setEnabled(enabled);
316
317 yearLabel.setEnabled(enabled);
318
319 if (enabled)
320 updateGui();
321 }
322
323 /** Changes the value of the 'exclusive' flag. If it is set to True, only one
324 * month can be selected. */
325 public void setExclusive(boolean exclusive)
326 {
327 if (this.exclusive == exclusive)
328 return;
329 selectedMonthsMap.clear();
330 this.exclusive = exclusive;
331 updateGui();
332 }
333
334 /** Returns true if the the month selector is in the 'exclusive' mode. */
335 public boolean isExclusive()
336 {
337 return exclusive;
338 }
339
340 /** Deselect all months. Does not notify any listeners that the moths are
341 being deselected.*/
342 public void clearAllSelections()
343 {
344 selectedMonthsMap.clear();
345 updateGui();
346 }
347
348 /** Returns true if all valid months in a current year are selected. */
349 public boolean isYearSelected()
350 {
351 if (exclusive)
352 return false;
353
354 DataManager dataManager = DataManager.getInstance();
355 Integer iYear = new Integer(cYear);
356 List<Integer> validMonths;
357 if (dataManager.getValidYears().contains(iYear))
358 validMonths = dataManager.getValidMonths(cYear);
359 else
360 validMonths = Collections.emptyList();
361
362 Set<Integer> selectedMonths;
363 if (selectedMonthsMap.keySet().contains(iYear))
364 selectedMonths = selectedMonthsMap.get(iYear);
365 else
366 selectedMonths = Collections.emptySet();
367
368 return selectedMonths.containsAll(validMonths);
369 }
370
371 /** Selects all available months in the currently selected year. */
372 public void selectYear()
373 {
374 if (exclusive || isYearSelected())
375 return;
376
377 DataManager dataManager = DataManager.getInstance();
378 Integer iYear = new Integer(cYear);
379
380 List<Integer> validMonths = new ArrayList<Integer>();
381 if (dataManager.getValidYears().contains(iYear))
382 validMonths.addAll(dataManager.getValidMonths(cYear));
383
384 Set<Integer> selectedMonths;
385 if (selectedMonthsMap.keySet().contains(iYear))
386 selectedMonths = selectedMonthsMap.get(iYear);
387 else
388 selectedMonths = new HashSet<Integer>();
389
390 validMonths.removeAll(selectedMonths);
391
392 for (Integer iMonth : validMonths)
393 {
394 monthToButtonMap.get(iMonth).setSelected(true);
395 selectedMonths.add(iMonth);
396 }
397
398 if (validMonths.size() > 0)
399 {
400 selectedMonthsMap.put(iYear, selectedMonths);
401 cMonth = -1;
402 notifyListenersSelected();
403 }
404 }
405
406 /** Deselects all months in the year. */
407 public void deselectYear()
408 {
409 DataManager dataManager = DataManager.getInstance();
410 Integer iYear = new Integer(cYear);
411
412 Set<Integer> selectedMonths;
413 if (selectedMonthsMap.keySet().contains(iYear))
414 selectedMonths = selectedMonthsMap.get(iYear);
415 else
416 return;
417
418 for (Integer iMonth : selectedMonths)
419 monthToButtonMap.get(iMonth).setSelected(false);
420
421 selectedMonths.clear();
422 selectedMonthsMap.put(iYear, selectedMonths);
423 cMonth = -1;
424 notifyListenersDeselected();
425 }
426
427 //========================== Event Handling ==============================//
428
429 /** Notifies all listeners that a month was selected */
430 private void notifyListenersSelected()
431 {
432 for (SelectionListener listener : listeners)
433 listener.monthSelected(cMonth, cYear);
434 }
435
436 /** Notifies all listeners that a month was deselected */
437 private void notifyListenersDeselected()
438 {
439 for (SelectionListener listener : listeners)
440 listener.monthDeselected(cMonth, cYear);
441 }
442
443 /** Notifies all listeners that the selected year has changed. */
444 private void notifyYearChanged()
445 {
446 for (SelectionListener listener : listeners)
447 listener.yearChanged(cYear);
448 }
449
450 /** Adds a Listener */
451 public void addSelectionListener(SelectionListener listener)
452 {
453 listeners.add(listener);
454 }
455
456 /** Removes a Listener */
457 public void removeSelectionListener(SelectionListener listener)
458 {
459 listeners.remove(listener);
460 }
461
462 //========================= Inner Classes =====================//
463
464 public interface SelectionListener
465 {
466 public void monthSelected(int cMonth, int cYear);
467
468 public void monthDeselected(int cMont, int cYear);
469
470 public void yearChanged(int cYear);
471 }
472 }