001    /*****************************************************************************
002    
003        jBudget.
004        Copyright (C) 2006-2008  Dmitri Petrov
005    
006        This program is free software: you can redistribute it and/or modify
007        it under the terms of the GNU General Public License as published by
008        the Free Software Foundation, either version 3 of the License, or
009        (at your option) any later version.
010    
011        This program is distributed in the hope that it will be useful,
012        but WITHOUT ANY WARRANTY; without even the implied warranty of
013        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014        GNU General Public License for more details.
015    
016        You should have received a copy of the GNU General Public License
017        along with this program.  If not, see <http://www.gnu.org/licenses/>.
018     
019    *****************************************************************************/
020    
021    /*
022     * BudgetEditor.java
023     *
024     * Created on March 30, 2006, 5:55 PM
025     */
026    package org.jbudget.gui.budget;
027    
028    import java.awt.BorderLayout;
029    import java.awt.Color;
030    import java.awt.Component;
031    import java.awt.Font;
032    import java.awt.Point;
033    import java.awt.event.ActionEvent;
034    import java.awt.event.ActionListener;
035    import java.awt.event.ItemEvent;
036    import java.awt.event.ItemListener;
037    import java.awt.event.MouseAdapter;
038    import java.awt.event.MouseEvent;
039    import java.awt.image.BufferedImage;
040    import java.util.ArrayList;
041    import java.util.List;
042    import javax.swing.Icon;
043    import javax.swing.JFrame;
044    import javax.swing.JMenuItem;
045    import javax.swing.JOptionPane;
046    import javax.swing.JPopupMenu;
047    import javax.swing.JScrollPane;
048    import javax.swing.JSeparator;
049    import javax.swing.JTree;
050    import javax.swing.ListSelectionModel;
051    import javax.swing.UIManager;
052    import javax.swing.event.TreeSelectionEvent;
053    import javax.swing.event.TreeSelectionListener;
054    import javax.swing.tree.TreePath;
055    import javax.swing.tree.TreeSelectionModel;
056    import org.jbudget.Core.Account;
057    import org.jbudget.Core.AutomaticTransaction;
058    import org.jbudget.Core.Budget;
059    import org.jbudget.Core.ExpenseAllocation;
060    import org.jbudget.Core.ExpenseCategory;
061    import org.jbudget.Core.IncomeSource;
062    import org.jbudget.Core.MoneyPit;
063    import org.jbudget.Core.User;
064    import org.jbudget.gui.GuiPreferences;
065    import org.jbudget.gui.components.JTreeStriped;
066    import org.jbudget.gui.templ.BudgetEditorTemplate;
067    import org.jbudget.gui.trans.AutoAllocationEditor;
068    import org.jbudget.gui.trans.AutoTransactionEditor;
069    import org.jbudget.gui.trans.models.IncomeListModel;
070    import org.jbudget.io.DataManager;
071    import org.jbudget.util.CurrencyFormater;
072    
073    /**
074     *  Creates a window that shows a graphical representation of a budget object
075     *  and allows editing of that object.
076     *
077     * @author petrov
078     */
079    public class BudgetEditor extends BudgetEditorTemplate
080    {
081    
082        final Budget budget;
083        /** Used to draw the budget tree */
084        final BudgetTreeModel treeModel;
085        /** Used to draw the income list */
086        final IncomeListModel incomeListModel;
087        /** A tree of the budget categories and allocations/deductions */
088        final JTree tree;
089        /** if true, the budget can be edited. Otherwise the editor works as a viewer*/
090        final boolean editable;
091        /** Renderer. */
092        private final BudgetTreeRenderer renderer;
093    
094        /** Creates a new instance of BudgetEditor */
095        public BudgetEditor(JFrame parent, Budget budget, boolean editable)
096        {
097            super();
098            setTitle("Budget Name: " + budget.getName() +
099                    ", ID: " + Integer.toString(budget.getID()));
100    
101            Icon icon = UIManager.getIcon(GuiPreferences.iconBudgetKey);
102            BufferedImage image = new BufferedImage(icon.getIconWidth(),
103                    icon.getIconHeight(),
104                    BufferedImage.TYPE_INT_RGB);
105    
106            icon.paintIcon(null, image.getGraphics(), 0, 0);
107    
108            setIconImage(image);
109    
110            this.budget = budget;
111            this.editable = editable;
112            treeModel = new BudgetTreeModel(budget);
113            incomeListModel = new IncomeListModel(budget);
114    
115            // creating the budget tree
116            tree = new JTreeStriped(treeModel);
117            renderer = new BudgetTreeRenderer(budget);
118            tree.setCellRenderer(renderer);
119            tree.setEditable(false);
120            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
121            tree.setRootVisible(false);
122            tree.putClientProperty("JTree.lineStyle", "Horizontal");
123    
124            // adding the tree to the gui    
125            JScrollPane treeView = new JScrollPane(tree);
126            innerTreePanel.setLayout(new BorderLayout());
127            innerTreePanel.add(treeView);
128    
129            // initializing the income list.
130            incomeSourcesList.setModel(incomeListModel);
131    
132            //default close policy -- do nothing
133            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
134    
135            //Making gui work.
136            allocationsCheckBox.addItemListener(new ItemListener()
137            {
138    
139                public void itemStateChanged(ItemEvent e)
140                {
141                    treeModel.setShowAllocations(allocationsCheckBox.isSelected());
142                }
143            });
144    
145            transactionsCheckBox.addItemListener(new ItemListener()
146            {
147    
148                public void itemStateChanged(ItemEvent e)
149                {
150                    treeModel.setShowTransactions(transactionsCheckBox.isSelected());
151                }
152            });
153    
154            cancelButton.addActionListener(new ActionListener()
155            {
156    
157                public void actionPerformed(ActionEvent e)
158                {
159                    setVisible(false);
160                    dispose();
161                }
162            });
163    
164            applyButton.addActionListener(new ActionListener()
165            {
166    
167                public void actionPerformed(ActionEvent e)
168                {
169                    setVisible(false);
170                    dispose();
171                }
172            });
173    
174            //Respondig to tree selections
175            tree.addTreeSelectionListener(new TreeSelectionListener()
176            {
177    
178                public void valueChanged(TreeSelectionEvent e)
179                {
180                    Object node = tree.getLastSelectedPathComponent();
181                    if (node instanceof ExpenseCategory)
182                        displayCategoryInfo((ExpenseCategory) node);
183                    else if (node instanceof Account)
184                        displayAccountInfo((Account) node);
185                    else if (node instanceof IncomeSource)
186                        displayIncomeSourceInfo((IncomeSource) node);
187                    else if (node instanceof ExpenseAllocation)
188                        displayAllocationInfo((ExpenseAllocation) node);
189                    else if (node instanceof AutomaticTransaction)
190                        displayTransactionInfo((AutomaticTransaction) node);
191                    else
192                        textArea.setText(null);
193                }
194            });
195    
196            //Responding to mouse events
197            if (editable)
198                tree.addMouseListener(new MouseAdapter()
199                {
200    
201                    @Override
202                    public void mousePressed(MouseEvent e)
203                    {
204                        popupChecker(e);
205                    }
206    
207                    @Override
208                    public void mouseReleased(MouseEvent e)
209                    {
210                        popupChecker(e);
211                    }
212    
213                    private void popupChecker(MouseEvent e)
214                    {
215                        if (e.isPopupTrigger())
216                        {
217                            int x = e.getX();
218                            int y = e.getY();
219                            tree.setSelectionRow(tree.getRowForLocation(x, y));
220                            TreePath path = tree.getSelectionPath();
221                            if ((path == null) || (path.getPathCount() == 0))
222                                return;
223    
224                            Object item = path.getLastPathComponent();
225    
226                            if (item == BudgetTreeModel.accounts)
227                                new AccountMenu(null, path, x, y);
228                            else if (item == BudgetTreeModel.expenseCategories)
229                                new AddRootCategoryMenu(tree, x, y);
230                            else if (item == BudgetTreeModel.incomeSources)
231                                new IncomeSourceMenu(tree, null, x, y);
232                            else if (item instanceof Account)
233                                new AccountMenu((Account) item, path, x, y);
234                            else if (item instanceof ExpenseCategory)
235                                new CategoryMenu((ExpenseCategory) item, path, x, y);
236                            else if (item instanceof IncomeSource)
237                                new IncomeSourceMenu(tree, (IncomeSource) item, x, y);
238                            else if (item instanceof ExpenseAllocation)
239                                new AllocationMenu((ExpenseAllocation) item, path, x, y);
240                            else if (item instanceof AutomaticTransaction)
241                                new AutoTransactionMenu((AutomaticTransaction) item, x, y);
242                        }
243                    }
244                });
245    
246            incomeSourcesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
247            if (editable)
248                incomeSourcesList.addMouseListener(new MouseAdapter()
249                {
250    
251                    @Override
252                    public void mousePressed(MouseEvent e)
253                    {
254                        popupChecker(e);
255                    }
256    
257                    @Override
258                    public void mouseReleased(MouseEvent e)
259                    {
260                        popupChecker(e);
261                    }
262    
263                    private void popupChecker(MouseEvent e)
264                    {
265                        if (e.isPopupTrigger())
266                        {
267                            int x = e.getX();
268                            int y = e.getY();
269    
270                            int index = incomeSourcesList.locationToIndex(new Point(x, y));
271                            incomeSourcesList.setSelectedIndex(index);
272                            IncomeSource is = null;
273                            if (index > -1)
274                            {
275                                java.util.List<IncomeSource> sources =
276                                        BudgetEditor.this.budget.getIncomeSources();
277                                is = sources.get(index);
278                            }
279    
280                            new IncomeSourceMenu(incomeSourcesList, is, x, y);
281                        }
282                    }
283                });
284    
285            newCategoryButton.setEnabled(editable);
286            newIncomeButton.setEnabled(editable);
287            registerAccountButton.setEnabled(editable);
288    
289            //Functionality for adding new root categories
290            newCategoryButton.addActionListener(new CategoryInserter());
291    
292            //Functionality for adding new Income Sources
293            newIncomeButton.addActionListener(new IncomeSourceInserter());
294    
295            //Functionality for registering accounts
296            registerAccountButton.addActionListener(new AccountInserter());
297    
298            textArea.setFont(new Font("Areal", Font.PLAIN, 16));
299            displaySummary();
300    
301            //displaying
302            if (editable)
303                applyButton.setText("OK");
304            else
305                applyButton.setText("Close");
306            pack();
307            setLocationRelativeTo(parent);
308            setVisible(true);
309        }
310    
311        //============================ helper methods ===================//
312        /**
313         * Displays information about selected ExpenseCategory
314         */
315        private void displayCategoryInfo(ExpenseCategory budgetCategory)
316        {
317            StringBuffer text = new StringBuffer();
318            text.append("Expense category: ");
319            text.append(budgetCategory.getName());
320            text.append("\nUsed by: ");
321            if (budgetCategory.getSelectUsers())
322            {
323                List<User> users = budgetCategory.getHolders();
324                if (users.isEmpty())
325                    text.append("nobody");
326                else
327                {
328                    boolean first = true;
329                    for (User u : users)
330                    {
331                        if (!first)
332                            text.append(", ");
333                        else
334                            first = false;
335                        text.append(u.getName());
336                    }
337                }
338            }
339            else
340                text.append("everybody");
341            text.append("\n\n");
342    
343    
344    
345            text.append("==== Allocations & Auto Transactions ====\n");
346            if (budgetCategory.getHoldsTransactions())
347            {
348                long mnAmount = budget.monthlyAllocationAmount(budgetCategory, false);
349                long yrAmount = budget.yearlyAllocationAmount(budgetCategory, false);
350                if (mnAmount > 0)
351                {
352                    text.append(CurrencyFormater.format(mnAmount));
353                    text.append(" per month (");
354                    text.append(CurrencyFormater.format(yrAmount));
355                    text.append(" per year) is allocated to this category.\n");
356                }
357                else
358                    text.append("No funds have been allocated to this category.\n");
359    
360                mnAmount = budget.monthlyAutoTrAmountDest(budgetCategory, false);
361                yrAmount = budget.yearlyAutoTrAmountDest(budgetCategory, false);
362                if (mnAmount > 0)
363                {
364                    text.append(CurrencyFormater.format(mnAmount));
365                    text.append(" per month (");
366                    text.append(CurrencyFormater.format(yrAmount));
367                    text.append(" per year) is automatically spent in this category.\n");
368                }
369                else if (mnAmount < 0)
370                {
371                    text.append(CurrencyFormater.format(-mnAmount));
372                    text.append(" per month (");
373                    text.append(CurrencyFormater.format(-yrAmount));
374                    text.append(" per year) is automatically refunded to this category.\n");
375                }
376                else
377                    text.append("No funds are automatically spent in this category.\n");
378            }
379            else
380                text.append("This expense category can not hold transactions.");
381    
382            java.util.List<ExpenseCategory> subcategories =
383                    budget.getSubcategories(budgetCategory);
384            if (subcategories.size() > 0)
385            {
386                long mnAmount = budget.monthlyAllocationAmount(budgetCategory, true);
387                long yrAmount = budget.yearlyAllocationAmount(budgetCategory, true);
388                if (mnAmount > 0)
389                {
390                    text.append(CurrencyFormater.format(mnAmount));
391                    text.append(" per month (");
392                    text.append(CurrencyFormater.format(yrAmount));
393                    if (budgetCategory.getHoldsTransactions())
394                        text.append(" per year) is allocated to this category and " +
395                                "all its subcategories.\n");
396                    else
397                        text.append(" per year) is allocated to the subcategories of this" +
398                                " expense category.\n");
399    
400                }
401                else
402                    if (budgetCategory.getHoldsTransactions())
403                        text.append("No funds have been allocated to this category or any " +
404                                "of its subcategories.\n");
405                    else
406                        text.append("No funds have been allocated to the subcategories " +
407                                "of this expense category.\n");
408    
409                mnAmount = budget.monthlyAutoTrAmountDest(budgetCategory, true);
410                yrAmount = budget.yearlyAutoTrAmountDest(budgetCategory, true);
411                if (mnAmount > 0)
412                {
413                    text.append(CurrencyFormater.format(mnAmount));
414                    text.append(" per month (");
415                    text.append(CurrencyFormater.format(yrAmount));
416                    if (budgetCategory.getHoldsTransactions())
417                        text.append(" per year) is automatically spent in this category " +
418                                "and its subcategories.\n");
419                    else
420                        text.append(" per year) is automatically spent in the subcategories" +
421                                " of this expense category.\n");
422    
423                }
424                else if (mnAmount < 0)
425                {
426                    text.append(CurrencyFormater.format(-mnAmount));
427                    text.append(" per month (");
428                    text.append(CurrencyFormater.format(-yrAmount));
429                    if (budgetCategory.getHoldsTransactions())
430                        text.append(" per year) is automatically refunded to this category " +
431                                "and its subcategories.\n");
432                    else
433                        text.append(" per year) is automatically refunded to the subcategories" +
434                                " of this expense category.\n");
435                }
436                else
437                    if (budgetCategory.getHoldsTransactions())
438                        text.append("No funds is automatically spent in this category " +
439                                "or any of its subcategories.\n");
440                    else
441                        text.append("No funds is automatically spent in the subcategories of" +
442                                " this expense category.\n");
443            }
444    
445    
446            text.append("\n==== Subcategories ====\n");
447            int size = subcategories.size();
448            if (size == 0)
449                text.append("This category has no subcategories");
450            else
451            {
452                if (size == 1)
453                    text.append("This category has one subcategory:\n");
454                else
455                {
456                    text.append("This category has ");
457                    text.append(Integer.toString(size));
458                    text.append(" subcategories:\n");
459                }
460                for (ExpenseCategory subcategory : subcategories)
461                {
462                    text.append("  ");
463                    text.append(subcategory.getName());
464                    text.append("\n");
465                }
466            }
467    
468            textArea.setText(text.toString());
469        }
470    
471        /** 
472         * Displays information about a selected Account
473         */
474        private void displayAccountInfo(Account account)
475        {
476    
477            StringBuffer text = new StringBuffer();
478            text.append("Account: ");
479            text.append(account.getName());
480            text.append("\nBelongs to: ");
481            List<User> users = account.getAccountHolders();
482            if (users.isEmpty())
483                text.append("nobody");
484            else
485            {
486                boolean first = true;
487                for (User u : users)
488                {
489                    if (!first)
490                        text.append(", ");
491                    else
492                        first = false;
493                    text.append(u.getName());
494                }
495            }
496            text.append("\n\n");
497            text.append("==== Auto Transactions ====\n");
498    
499            long mnAmountTo = budget.monthlyAutoTrAmountDest(new MoneyPit(account));
500            long yrAmountTo = budget.yearlyAutoTrAmountDest(new MoneyPit(account));
501    
502            long mnAmountFrom = budget.monthlyAutoTrAmountSource(new MoneyPit(account));
503            long yrAmountFrom = budget.yearlyAutoTrAmountSource(new MoneyPit(account));
504    
505            if (mnAmountTo < 0)
506            {
507                mnAmountFrom -= mnAmountTo;
508                mnAmountTo = 0L;
509                yrAmountFrom -= yrAmountTo;
510                yrAmountTo = 0L;
511            }
512    
513            if (mnAmountFrom < 0)
514            {
515                mnAmountTo -= mnAmountFrom;
516                mnAmountFrom = 0L;
517                yrAmountTo -= yrAmountFrom;
518                yrAmountFrom = 0L;
519            }
520    
521            if (mnAmountTo > 0)
522            {
523                text.append(CurrencyFormater.format(mnAmountTo));
524                text.append(" per month (");
525                text.append(CurrencyFormater.format(yrAmountTo));
526                text.append(" per year) is automatically transferred to this account.\n");
527            }
528            else
529                text.append("No funds are automatically transferred to this account.\n");
530    
531            if (mnAmountFrom > 0)
532            {
533                text.append(CurrencyFormater.format(mnAmountFrom));
534                text.append(" per month (");
535                text.append(CurrencyFormater.format(yrAmountFrom));
536                text.append(
537                        " per year) is automatically transferred from this account.\n");
538            }
539            else
540                text.append(
541                        "No funds are automatically transferred from this account.\n");
542    
543            textArea.setText(text.toString());
544        }
545    
546        /** 
547         * Displays information about a selected IncomeSource
548         */
549        private void displayIncomeSourceInfo(IncomeSource iSource)
550        {
551            StringBuffer text = new StringBuffer();
552            text.append("Income Source: ");
553            text.append(iSource.getName());
554            text.append("\n\n");
555            text.append("==== Auto Transactions ====\n");
556    
557            long mnAmountTo = iSource.getMonthlyAmount();
558            long yrAmountTo = iSource.getYearlyAmount();
559    
560            long mnAmountFrom =
561                    budget.monthlyAutoTrAmountSource(new MoneyPit(iSource, budget));
562            long yrAmountFrom =
563                    budget.yearlyAutoTrAmountSource(new MoneyPit(iSource, budget));
564    
565    
566    
567            if (mnAmountTo > 0)
568            {
569                text.append(CurrencyFormater.format(mnAmountTo));
570                text.append(" per month (");
571                text.append(CurrencyFormater.format(yrAmountTo));
572                text.append(" per year) is generated by this income source.\n");
573            }
574            else
575                text.append("No funds are generated by this income source.\n");
576    
577            if (mnAmountFrom > 0)
578            {
579                text.append(CurrencyFormater.format(mnAmountFrom));
580                text.append(" per month (");
581                text.append(CurrencyFormater.format(yrAmountFrom));
582                text.append(
583                        " per year) is automatically transferred from this income source.\n");
584            }
585            else if (mnAmountFrom < 0)
586            {
587                text.append(CurrencyFormater.format(-mnAmountFrom));
588                text.append(" per month (");
589                text.append(CurrencyFormater.format(-yrAmountFrom));
590                text.append(
591                        " per year) is automatically transferred to this income source.\n" +
592                        "YOU SHOULD NOT DO THAT!");
593            }
594            else
595                text.append(
596                        "No funds are automatically transferred from this account.\n");
597    
598            textArea.setText(text.toString());
599        }
600    
601        /**
602         * Displays information about selected ExpenseAllocation
603         */
604        private void displayAllocationInfo(ExpenseAllocation allocation)
605        {
606            StringBuffer text = new StringBuffer();
607            AutomaticTransaction.Type type = allocation.getType();
608            long amount = allocation.getAmount();
609            int time = allocation.getTime();
610            text.append("Allocation of ");
611            text.append(CurrencyFormater.format(amount));
612            text.append(" per ");
613            if (type == AutomaticTransaction.Type.DAILY)
614                text.append("day.");
615            else if (type == AutomaticTransaction.Type.WEEKLY)
616            {
617                text.append("week.\n");
618                text.append("Applied on the ");
619                if (time == 1)
620                    text.append("first");
621                else if (time == -1)
622                    text.append("last");
623                else
624                    text.append(Integer.toString(time));
625                text.append(" day of the week.");
626            }
627            else if (type == AutomaticTransaction.Type.MONTHLY)
628            {
629                text.append("month.\n");
630                text.append("Applied on the ");
631                if (time == 1)
632                    text.append("first");
633                else if (time == -1)
634                    text.append("last");
635                else
636                    text.append(Integer.toString(time));
637                text.append(" day of the month.");
638            }
639            else if (type == AutomaticTransaction.Type.YEARLY)
640            {
641                text.append("year.\n");
642                text.append("Applied on the ");
643                if (time == 1)
644                    text.append("first");
645                else if (time == -1)
646                    text.append("last");
647                else
648                    text.append(Integer.toString(time));
649                text.append(" day of the year.");
650            }
651            textArea.setText(text.toString());
652        }
653    
654        /** Displays information about selected AutomaticTransactions */
655        private void displayTransactionInfo(AutomaticTransaction autoTransaction)
656        {
657            StringBuffer text = new StringBuffer();
658            AutomaticTransaction.Type type = autoTransaction.getType();
659            long amount = autoTransaction.getAmount();
660            int time = autoTransaction.getTime();
661            text.append("Transfer of ");
662            text.append(CurrencyFormater.format(amount));
663            text.append(" per ");
664            if (type == AutomaticTransaction.Type.DAILY)
665                text.append("day.");
666            else if (type == AutomaticTransaction.Type.WEEKLY)
667            {
668                text.append("week.\n");
669                text.append("Applied on the ");
670                if (time == 1)
671                    text.append("first");
672                else if (time == -1)
673                    text.append("last");
674                else
675                    text.append(Integer.toString(time));
676                text.append(" day of the week.");
677            }
678            else if (type == AutomaticTransaction.Type.MONTHLY)
679            {
680                text.append("month.\n");
681                text.append("Applied on the ");
682                if (time == 1)
683                    text.append("first");
684                else if (time == -1)
685                    text.append("last");
686                else
687                    text.append(Integer.toString(time));
688                text.append(" day of the month.");
689            }
690            else if (type == AutomaticTransaction.Type.YEARLY)
691            {
692                text.append("year.\n");
693                text.append("Applied on the ");
694                if (time == 1)
695                    text.append("first");
696                else if (time == -1)
697                    text.append("last");
698                else
699                    text.append(Integer.toString(time));
700                text.append(" day of the year.");
701            }
702            text.append("\n");
703            MoneyPit source = autoTransaction.getSource();
704            if (source != null)
705            {
706                text.append("Source ");
707                text.append(source.getNameLong());
708            }
709            else
710                text.append("No Source");
711            text.append("\n");
712            MoneyPit dest = autoTransaction.getDestination();
713            if (dest != null)
714            {
715                text.append("Destination ");
716                text.append(dest.getNameLong());
717            }
718            else
719                text.append("No Destination");
720            textArea.setText(text.toString());
721        }
722    
723        /** Displays the monthly and yearly summary */
724        private void displaySummary()
725        {
726            long monthlyIncome = budget.monthlyIncome();
727            long yearlyIncome = budget.yearlyIncome();
728            long monthlyAllocated = budget.monthlyAllocationAmount();
729            long yearlyAllocated = budget.yearlyAllocationAmount();
730            long monthlySavings = monthlyIncome - monthlyAllocated;
731            long yearlySavings = yearlyIncome - yearlyAllocated;
732            long monthlySpent = budget.monthlySpentAmount();
733            long yearlySpent = budget.yearlySpentAmount();
734            long monthlyAvailable = monthlyAllocated - monthlySpent;
735            long yearlyAvailable = yearlyAllocated - yearlySpent;
736    
737            monthlyIncomeText.setText(CurrencyFormater.format(monthlyIncome));
738            yearlyIncomeText.setText(CurrencyFormater.format(yearlyIncome));
739    
740            monthlyAllocatedText.setText(CurrencyFormater.format(monthlyAllocated));
741            yearlyAllocatedText.setText(CurrencyFormater.format(yearlyAllocated));
742    
743            monthlySpentText.setText(CurrencyFormater.format(monthlySpent));
744            yearlySpentText.setText(CurrencyFormater.format(yearlySpent));
745    
746            if (monthlySavings < 0)
747                monthlySavingsText.setForeground(Color.RED);
748            else
749                monthlySavingsText.setForeground(Color.BLACK);
750            monthlySavingsText.setText(CurrencyFormater.format(monthlySavings));
751    
752            if (yearlySavings < 0)
753                yearlySavingsText.setForeground(Color.RED);
754            else
755                yearlySavingsText.setForeground(Color.BLACK);
756            yearlySavingsText.setText(CurrencyFormater.format(yearlySavings));
757    
758            if (monthlyAvailable < 0)
759                monthlyAvailableText.setForeground(Color.RED);
760            else
761                monthlyAvailableText.setForeground(Color.BLACK);
762            monthlyAvailableText.setText(
763                    CurrencyFormater.format(monthlyAvailable));
764    
765            if (yearlyAvailable < 0)
766                yearlyAvailableText.setForeground(Color.RED);
767            else
768                yearlyAvailableText.setForeground(Color.BLACK);
769            yearlyAvailableText.setText(CurrencyFormater.format(yearlyAvailable));
770        }
771    
772        //========================================================================//
773        
774        private void removeAllocation(ExpenseAllocation allocation,
775                                       ExpenseCategory category)
776        {
777            int index = treeModel.getIndexOfChild(category, allocation);
778            TreePath path = treeModel.getTreePath(allocation, false);
779    
780            budget.removeAllocation(allocation);
781            if (index >= 0)
782                treeModel.signalNodeRemoved(path, index);
783        }
784    
785        private void removeAutoTransaction(AutomaticTransaction autoTransaction)
786        {
787            MoneyPit source = autoTransaction.getSource();
788    
789            // a path to the auto transaction through a source of the transaction.
790            TreePath sourcePath = null;
791            if (source != null)
792                sourcePath = treeModel.getTreePath(autoTransaction, true);
793    
794            MoneyPit destination = autoTransaction.getDestination();
795    
796            // a path to the auto transaction through a destination of the transaction.
797            TreePath destinationPath = null;
798            if (destination != null && destination != source)
799                destinationPath = treeModel.getTreePath(autoTransaction, false);
800    
801            int index1 = -1;
802            if (sourcePath != null)
803                index1 = treeModel.getIndexOfChild(
804                        source.getContent(), autoTransaction);
805            int index2 = -1;
806            if (destinationPath != null)
807                index2 = treeModel.getIndexOfChild(
808                        destination.getContent(), autoTransaction);
809    
810            budget.removeAutoTransaction(autoTransaction);
811            if (index1 > -1)
812                treeModel.signalNodeRemoved(sourcePath, index1);
813            if (index2 > -1)
814                treeModel.signalNodeRemoved(destinationPath, index2);
815        }
816    
817        private void addAutoTransaction(AutomaticTransaction autoTransaction)
818        {
819            budget.addAutoTransaction(autoTransaction);
820            MoneyPit source = autoTransaction.getSource();
821    
822            // a path to the auto transaction through a source of the transaction.
823            TreePath sourcePath = null;
824            if (source != null)
825                sourcePath = treeModel.getTreePath(autoTransaction, true);
826    
827            MoneyPit destination = autoTransaction.getDestination();
828    
829            // a path to the auto transaction through a destination of the transaction.
830            TreePath destinationPath = null;
831            if (destination != null && destination != source)
832                destinationPath = treeModel.getTreePath(autoTransaction, false);
833    
834            int index1 = -1;
835            if (sourcePath != null)
836                index1 = treeModel.getIndexOfChild(
837                        source.getContent(), autoTransaction);
838            int index2 = -1;
839            if (destinationPath != null)
840                index2 = treeModel.getIndexOfChild(
841                        destination.getContent(), autoTransaction);
842    
843            if (index1 > -1)
844                treeModel.signalNodeInserted(sourcePath, index1);
845            if (index2 > -1)
846                treeModel.signalNodeInserted(destinationPath, index2);
847        }
848    
849        private void removeIncomeSource(IncomeSource incomeSource)
850        {
851            int index = incomeListModel.getIndexOf(incomeSource);
852    
853            TreePath path = (new TreePath(treeModel.getRoot())).pathByAddingChild(BudgetTreeModel.incomeSources);
854            int index1 = treeModel.getIndexOfChild(BudgetTreeModel.incomeSources,
855                    incomeSource);
856            boolean result = budget.removeIncomeSource(incomeSource);
857            if (!result)
858            {
859                int option = JOptionPane.showConfirmDialog(this,
860                        "There are automatic transactions associated with \n " +
861                        "the income source you are trying to remove.\n " +
862                        "They will also be removed.\n " +
863                        "Do you want to proceed?", "Confirm", JOptionPane.YES_NO_OPTION);
864                if (option == JOptionPane.NO_OPTION)
865                    return;
866                List<AutomaticTransaction> autoTrList =
867                        new ArrayList<AutomaticTransaction>();
868                autoTrList.addAll(
869                        budget.getAutoTransactionsDest(new MoneyPit(incomeSource, budget)));
870                autoTrList.addAll(
871                        budget.getAutoTransactionsSource(new MoneyPit(incomeSource, budget)));
872                for (AutomaticTransaction autoTr : autoTrList)
873                    this.removeAutoTransaction(autoTr);
874                result = budget.removeIncomeSource(incomeSource, true);
875            }
876    
877            if (!result)
878                JOptionPane.showMessageDialog(this,
879                        "Could not remove the income source", "Error",
880                        JOptionPane.ERROR_MESSAGE);
881    
882            incomeListModel.signalRemoved(index);
883            if (index1 >= 0)
884                treeModel.signalNodeRemoved(path.pathByAddingChild(incomeSource), index1);
885            else
886                treeModel.signalStructureChanged();
887        }
888    
889        private void addIncomeSource(IncomeSource incomeSource)
890        {
891            Object[] pathArray = {BudgetTreeModel.root,
892                BudgetTreeModel.incomeSources,
893                incomeSource
894            };
895            TreePath path = new TreePath(pathArray);
896    
897            budget.addIncomeSource(incomeSource);
898            incomeListModel.signalAdded(
899                    incomeListModel.getIndexOf(incomeSource));
900            displaySummary();
901    
902            int index = treeModel.getIndexOfChild(BudgetTreeModel.incomeSources,
903                    incomeSource);
904            if (index >= 0)
905                treeModel.signalNodeInserted(path, index);
906            else
907                treeModel.signalStructureChanged();
908        }
909    
910        private void removeAccount(Account account)
911        {
912    
913            List<Account> cashAccounts = DataManager.getInstance().getCashAccounts();
914            if (cashAccounts.contains(account))
915            {
916                JOptionPane.showMessageDialog(this,
917                        "Cash accounts can not be removed.", "Warning",
918                        JOptionPane.WARNING_MESSAGE);
919                return;
920            }
921    
922            Object[] pathArray = {BudgetTreeModel.root,
923                BudgetTreeModel.accounts,
924                account
925            };
926            TreePath path = new TreePath(pathArray);
927    
928            int index1 = treeModel.getIndexOfChild(BudgetTreeModel.accounts,
929                    account);
930            boolean result = budget.unregisterAccount(account, false);
931            if (!result)
932            {
933                int option = JOptionPane.showConfirmDialog(this,
934                        "There are automatic transactions associated with \n " +
935                        "the account you are trying to remove.\n " +
936                        "They will also be removed.\n " +
937                        "Do you want to proceed?", "Confirm", JOptionPane.YES_NO_OPTION);
938                if (option == JOptionPane.NO_OPTION)
939                    return;
940                List<AutomaticTransaction> autoTrList =
941                        new ArrayList<AutomaticTransaction>();
942                autoTrList.addAll(
943                        budget.getAutoTransactionsDest(new MoneyPit(account)));
944                autoTrList.addAll(
945                        budget.getAutoTransactionsSource(new MoneyPit(account)));
946                for (AutomaticTransaction autoTr : autoTrList)
947                    this.removeAutoTransaction(autoTr);
948                result = budget.unregisterAccount(account, true);
949            }
950    
951            if (!result)
952                JOptionPane.showMessageDialog(this,
953                        "Could not remove the account", "Error",
954                        JOptionPane.ERROR_MESSAGE);
955    
956            if (index1 >= 0)
957                treeModel.signalNodeRemoved(path, index1);
958            else
959                treeModel.signalStructureChanged();
960        }
961    
962        private void addAccount(Account account)
963        {
964            Object[] pathArray = {BudgetTreeModel.root,
965                BudgetTreeModel.accounts,
966                account
967            };
968            TreePath path = new TreePath(pathArray);
969    
970            budget.registerAccount(account);
971            int index = treeModel.getIndexOfChild(BudgetTreeModel.accounts,
972                    account);
973            if (index >= 0)
974                treeModel.signalNodeInserted(path, index);
975            else
976                treeModel.signalStructureChanged();
977        }
978    
979        //============================== Events ==================================//
980        /** Registers a listener with the apply button. The listener will receive
981         *  events when the "OK" or "Close" button is clicked.
982         */
983        public void addOkListener(ActionListener listener)
984        {
985            applyButton.addActionListener(listener);
986        }
987    
988        /** @see #addOkListener(ActionListener) */
989        public void removeOkListener(ActionListener listener)
990        {
991            applyButton.removeActionListener(listener);
992        }
993    
994        //============================ nested classes ============================//
995        /** a class that creates a popup menu for an Account */
996        private class AccountMenu
997        {
998    
999            final Account account;
1000    
1001            /** Creates a JMenu and displays it */
1002            AccountMenu(Account account,
1003                        TreePath path, int x, int y)
1004            {
1005                this.account = account;
1006    
1007                assert account == null || path.getLastPathComponent() == account :
1008                        "Inconsistent data in the AccountMenu constructor";
1009    
1010                JPopupMenu menu = new JPopupMenu();
1011                JMenuItem add = new JMenuItem("Register");
1012                JMenuItem remove = new JMenuItem("Remove");
1013                JMenuItem transaction = new JMenuItem("Add Transaction");
1014    
1015                add.addActionListener(new AccountInserter());
1016                remove.addActionListener(new AccountRemover(account));
1017    
1018                transaction.addActionListener(new ActionListener()
1019                {
1020    
1021                    public void actionPerformed(ActionEvent e)
1022                    {
1023                        AutoTransactionEditor editor = new AutoTransactionEditor(
1024                                BudgetEditor.this, budget);
1025                        editor.addActionListener(new ActionListener()
1026                        {
1027    
1028                            public void actionPerformed(ActionEvent event)
1029                            {
1030                                AutoTransactionEditor editor =
1031                                        (AutoTransactionEditor) (event.getSource());
1032                                assert editor.getNewAutoTransaction() != null : "No new deduction";
1033                                addAutoTransaction(editor.getNewAutoTransaction());
1034                                displaySummary();
1035                            }
1036                        });
1037                    }
1038                });
1039    
1040                remove.setEnabled(account != null);
1041    
1042                menu.add(transaction);
1043                menu.add(new JSeparator());
1044                menu.add(add);
1045                menu.add(remove);
1046    
1047                menu.show(tree, x, y);
1048            }
1049        }
1050    
1051        /** a class that creates a popup menu for an expense category */
1052        private class CategoryMenu
1053        {
1054    
1055            final ExpenseCategory expenseCategory;
1056            final TreePath path;
1057            final Object parent;
1058            final int index;
1059    
1060            /** Creates a JMenu and displays it */
1061            CategoryMenu(ExpenseCategory theExpenseCategory,
1062                         TreePath thePath, int x, int y)
1063            {
1064                expenseCategory = theExpenseCategory;
1065                path = thePath;
1066                parent = path.getParentPath().getLastPathComponent();
1067                index = BudgetEditor.this.treeModel.getIndexOfChild(
1068                        parent, expenseCategory);
1069    
1070                assert path.getLastPathComponent() == expenseCategory :
1071                        "Inconsistent data in the CategoryMenu constructor";
1072    
1073                JPopupMenu menu = new JPopupMenu();
1074                JMenuItem edit = new JMenuItem("Edit");
1075                JMenuItem remove = new JMenuItem("Remove");
1076                JMenuItem subcategory = new JMenuItem("New Subcategory");
1077                JMenuItem allocation = new JMenuItem("New Allocation");
1078                JMenuItem transaction = new JMenuItem("New Auto Transaction");
1079    
1080                // Adding functionality to the menues.
1081                edit.addActionListener(new ActionListener()
1082                {
1083    
1084                    public void actionPerformed(ActionEvent e)
1085                    {
1086                        CategoryEditor editor = new CategoryEditor(BudgetEditor.this,
1087                                expenseCategory);
1088                        editor.addActionListener(new ActionListener()
1089                        {
1090    
1091                            public void actionPerformed(ActionEvent ev)
1092                            {
1093                                CategoryEditor editor = (CategoryEditor) (ev.getSource());
1094    
1095                                ExpenseCategory category = editor.getCategory();
1096                                if (!category.getHoldsTransactions())
1097                                {
1098                                    List<AutomaticTransaction> atl =
1099                                            new ArrayList<AutomaticTransaction>();
1100                                    atl.addAll(budget.getAutoTransactionsSource(
1101                                            new MoneyPit(category, budget)));
1102                                    for (AutomaticTransaction at : atl)
1103                                        BudgetEditor.this.removeAutoTransaction(at);
1104    
1105                                    atl.clear();
1106    
1107                                    atl.addAll(budget.getAutoTransactionsDest(
1108                                            new MoneyPit(category, budget)));
1109                                    for (AutomaticTransaction at : atl)
1110                                        BudgetEditor.this.removeAutoTransaction(at);
1111    
1112                                    List<ExpenseAllocation> eal = new ArrayList<ExpenseAllocation>();
1113                                    eal.addAll(budget.getAllocations(category));
1114                                    for (ExpenseAllocation ea : eal)
1115                                        BudgetEditor.this.removeAllocation(ea, category);
1116                                }
1117                                //Updating the budget tree.
1118                                BudgetEditor.this.treeModel.signalNodeChanged(path, index);
1119                            }
1120                        });
1121                    }
1122                });
1123    
1124                remove.addActionListener(new ActionListener()
1125                {
1126    
1127                    public void actionPerformed(ActionEvent e)
1128                    {
1129                        CategoryRemoveDialog dialog =
1130                                new CategoryRemoveDialog(BudgetEditor.this,
1131                                expenseCategory.getName());
1132                        dialog.addActionListener(new ActionListener()
1133                        {
1134    
1135                            public void actionPerformed(ActionEvent e)
1136                            {
1137    
1138                                CategoryRemoveDialog dialog =
1139                                        (CategoryRemoveDialog) (e.getSource());
1140    
1141                                int ind = treeModel.getIndexOfChild(parent, expenseCategory);
1142    
1143                                budget.removeCategory(expenseCategory, dialog.recursive,
1144                                        dialog.removeAllocations, dialog.inheritAllocations);
1145    
1146                                treeModel.signalNodeRemoved(path, ind);
1147                                displaySummary();
1148                            }
1149                        });
1150                    }
1151                });
1152    
1153                subcategory.addActionListener(new CategoryInserter(expenseCategory, path));
1154    
1155                allocation.addActionListener(new ActionListener()
1156                {
1157                    public void actionPerformed(ActionEvent e)
1158                    {
1159                        AutoAllocationEditor 
1160                            editor = new AutoAllocationEditor(BudgetEditor.this,
1161                                                              budget, 
1162                                                              null,
1163                                                              expenseCategory);
1164                        editor.addActionListener(new ActionListener()
1165                        {
1166                            public void actionPerformed(ActionEvent event)
1167                            {
1168                                AutoAllocationEditor editor = 
1169                                        (AutoAllocationEditor) (event.getSource());
1170                                assert editor.getNewAllocation() != null : "No new allocation";
1171                                budget.addAllocation(editor.getNewAllocation());
1172    
1173                                // If deductions are shown on the tree signal the 
1174                                // tree model that a new node was inserted.
1175                                if (treeModel.getShowAllcations())
1176                                {
1177                                    int index = treeModel.getIndexOfChild(
1178                                            expenseCategory, editor.getNewAllocation());
1179                                    assert index >= 0;
1180                                    treeModel.signalNodeInserted(
1181                                            path.pathByAddingChild(editor.getNewAllocation()), index);
1182                                }
1183    
1184                                //reselect the node to update the information in the text area.
1185                                tree.clearSelection();
1186                                tree.addSelectionPath(path);
1187                                displaySummary();
1188                            }
1189                        });
1190                    }
1191                });
1192    
1193                transaction.addActionListener(new ActionListener()
1194                {
1195                    public void actionPerformed(ActionEvent e)
1196                    {
1197                        AutoTransactionEditor editor = new AutoTransactionEditor(
1198                                                          BudgetEditor.this,budget);
1199                        
1200                        editor.addActionListener(new ActionListener()
1201                        {
1202                            public void actionPerformed(ActionEvent event)
1203                            {
1204                                AutoTransactionEditor editor =
1205                                        (AutoTransactionEditor) (event.getSource());
1206                                assert editor.getNewAutoTransaction() != null : "No new deduction";
1207                                addAutoTransaction(editor.getNewAutoTransaction());
1208                                //reselect the node to update the information in the text area.
1209                                tree.clearSelection();
1210                                tree.addSelectionPath(path.getParentPath());
1211                                displaySummary();
1212                            }
1213                        });
1214                    }
1215                });
1216    
1217                menu.add(edit);
1218                menu.add(remove);
1219                menu.add(new JSeparator());
1220                menu.add(subcategory);
1221                if (expenseCategory.getHoldsTransactions())
1222                {
1223                    menu.add(allocation);
1224                    menu.add(transaction);
1225                }
1226    
1227                menu.show(tree, x, y);
1228            }
1229        }
1230    
1231        /** a class that creates a popup menu for adding root expense categories */
1232        private class AddRootCategoryMenu
1233        {
1234    
1235            AddRootCategoryMenu(Component parent, int x, int y)
1236            {
1237                JPopupMenu menu = new JPopupMenu();
1238                JMenuItem add = new JMenuItem("New Category");
1239                add.setToolTipText("Create new root expense category");
1240    
1241                add.addActionListener(new CategoryInserter(null, null));
1242    
1243                menu.add(add);
1244                menu.show(parent, x, y);
1245            }
1246        }
1247    
1248        /** a class that creates a pupup menu for an allocation */
1249        private class AllocationMenu
1250        {
1251    
1252            final ExpenseAllocation allocation;
1253            final ExpenseCategory category;
1254            final TreePath path;
1255    
1256            /** Creates a JMenu and displays it */
1257            AllocationMenu(ExpenseAllocation theAllocation, TreePath treePath,
1258                           int x, int y)
1259            {
1260                this.allocation = theAllocation;
1261                this.path = treePath;
1262                category =
1263                        (ExpenseCategory) path.getParentPath().getLastPathComponent();
1264    
1265                JPopupMenu menu = new JPopupMenu();
1266                JMenuItem edit = new JMenuItem("Edit");
1267                JMenuItem remove = new JMenuItem("Remove");
1268    
1269                remove.addActionListener(new ActionListener()
1270                {
1271    
1272                    public void actionPerformed(ActionEvent e)
1273                    {
1274                        removeAllocation(allocation, category);
1275                        displaySummary();
1276                    }
1277                });
1278    
1279                edit.addActionListener(new ActionListener()
1280                {
1281    
1282                    public void actionPerformed(ActionEvent e)
1283                    {
1284                        AutoAllocationEditor editor = new AutoAllocationEditor(BudgetEditor.this,
1285                                budget, allocation);
1286                        editor.addActionListener(new ActionListener()
1287                        {
1288    
1289                            public void actionPerformed(ActionEvent event)
1290                            {
1291                                AutoAllocationEditor editor = (AutoAllocationEditor) (event.getSource());
1292                                int index = treeModel.getIndexOfChild(category, allocation);
1293                                budget.replaceAllocation(allocation, editor.getNewAllocation());
1294                                treeModel.signalNodeChanged(path, index);
1295                                tree.clearSelection();
1296                                TreePath newPath = path.getParentPath().pathByAddingChild(
1297                                        editor.getNewAllocation());
1298                                tree.addSelectionPath(newPath);
1299                                displaySummary();
1300                            }
1301                        });
1302                    }
1303                });
1304    
1305                menu.add(edit);
1306                menu.add(remove);
1307    
1308                menu.show(tree, x, y);
1309            }
1310        }
1311    
1312        /** a class that creates a popup menu for an automatic transaction */
1313        private class AutoTransactionMenu
1314        {
1315    
1316            final AutomaticTransaction autoTransaction;
1317            final int x;
1318            final int y;
1319    
1320            /** Creates a JMenu and displays it */
1321            AutoTransactionMenu(AutomaticTransaction autoTransaction, int x, int y)
1322            {
1323                this.autoTransaction = autoTransaction;
1324                this.x = x;
1325                this.y = y;
1326    
1327                JPopupMenu menu = new JPopupMenu();
1328                JMenuItem edit = new JMenuItem("Edit");
1329                JMenuItem remove = new JMenuItem("Remove");
1330    
1331                remove.addActionListener(new ActionListener()
1332                {
1333    
1334                    public void actionPerformed(ActionEvent e)
1335                    {
1336                        removeAutoTransaction(AutoTransactionMenu.this.autoTransaction);
1337                        displaySummary();
1338                    }
1339                });
1340    
1341                edit.addActionListener(new ActionListener()
1342                {
1343    
1344                    public void actionPerformed(ActionEvent e)
1345                    {
1346                        AutoTransactionEditor editor = new AutoTransactionEditor(
1347                                BudgetEditor.this, budget,
1348                                AutoTransactionMenu.this.autoTransaction);
1349                        editor.addActionListener(new ActionListener()
1350                        {
1351    
1352                            public void actionPerformed(ActionEvent event)
1353                            {
1354                                TreePath path = tree.getSelectionPath();
1355                                AutoTransactionEditor editor =
1356                                        (AutoTransactionEditor) (event.getSource());
1357                                removeAutoTransaction(AutoTransactionMenu.this.autoTransaction);
1358                                addAutoTransaction(editor.getNewAutoTransaction());
1359                                tree.clearSelection();
1360                                tree.addSelectionPath(path.getParentPath());
1361                                displaySummary();
1362                            }
1363                        });
1364                    }
1365                });
1366    
1367                menu.add(edit);
1368                menu.add(remove);
1369    
1370                menu.show(tree, x, y);
1371            }
1372        }
1373    
1374        /** a class that creates a popup menu for an income sources */
1375        private class IncomeSourceMenu
1376        {
1377    
1378            final IncomeSource incomeSource;
1379            final int x;
1380            final int y;
1381            final Component parent;
1382    
1383            IncomeSourceMenu(Component parent, IncomeSource incomeSource, int x, int y)
1384            {
1385                this.parent = parent;
1386                this.incomeSource = incomeSource;
1387                this.x = x;
1388                this.y = y;
1389    
1390                JPopupMenu menu = new JPopupMenu();
1391                JMenuItem add = new JMenuItem("New Income");
1392                JMenuItem remove = new JMenuItem("Remove");
1393                JMenuItem transaction = new JMenuItem("Add Transaction");
1394    
1395                remove.addActionListener(new ActionListener()
1396                {
1397    
1398                    public void actionPerformed(ActionEvent e)
1399                    {
1400                        removeIncomeSource(IncomeSourceMenu.this.incomeSource);
1401                    }
1402                });
1403    
1404                add.addActionListener(new IncomeSourceInserter());
1405    
1406                transaction.addActionListener(new ActionListener()
1407                {
1408    
1409                    public void actionPerformed(ActionEvent e)
1410                    {
1411                        AutoTransactionEditor editor = new AutoTransactionEditor(
1412                                BudgetEditor.this, budget);
1413                        editor.addActionListener(new ActionListener()
1414                        {
1415    
1416                            public void actionPerformed(ActionEvent event)
1417                            {
1418                                AutoTransactionEditor editor =
1419                                        (AutoTransactionEditor) (event.getSource());
1420                                assert editor.getNewAutoTransaction() != null : "No new deduction";
1421                                addAutoTransaction(editor.getNewAutoTransaction());
1422                                displaySummary();
1423                            }
1424                        });
1425                    }
1426                });
1427    
1428    
1429                if (incomeSource == null)
1430                    remove.setEnabled(false);
1431    
1432                menu.add(transaction);
1433                menu.add(new JSeparator());
1434                menu.add(remove);
1435                menu.add(add);
1436    
1437                menu.show(parent, x, y);
1438            }
1439        }
1440    
1441        /** a class that handles events related to adding budget categories */
1442        private class CategoryInserter implements ActionListener
1443        {
1444    
1445            /** parent category. Can be null if the category to be added is 
1446             * a root category and thus has no parent
1447             */
1448            final ExpenseCategory parentCategory;
1449            /** The tree path to the parent category. null if the parentCategory
1450             * is null.
1451             */
1452            final TreePath path;
1453    
1454            CategoryInserter(ExpenseCategory theParentCategory, TreePath thePath)
1455            {
1456                parentCategory = theParentCategory;
1457                if (thePath == null)
1458                    path = (new TreePath(treeModel.getRoot()))
1459                              .pathByAddingChild(BudgetTreeModel.expenseCategories);
1460                else
1461                    path = thePath;
1462            }
1463    
1464            CategoryInserter()
1465            {
1466                parentCategory = null;
1467                path = (new TreePath(treeModel.getRoot()))
1468                              .pathByAddingChild(BudgetTreeModel.expenseCategories);
1469            }
1470    
1471            public void actionPerformed(ActionEvent e)
1472            {
1473                CategoryEditor editor = new CategoryEditor(BudgetEditor.this, null);
1474                editor.addActionListener(new ActionListener()
1475                {
1476    
1477                    public void actionPerformed(ActionEvent e)
1478                    {
1479                        CategoryEditor editor = (CategoryEditor) (e.getSource());
1480                        ExpenseCategory newCategory = editor.getCategory();
1481                        assert newCategory != null : "No new category";
1482    
1483                        if (parentCategory != null)
1484                            budget.addSubcategory(
1485                                    parentCategory, newCategory, false);
1486                        else
1487                            budget.addRootExpenseCategory(newCategory, false);
1488    
1489                        int index = treeModel.getIndexOfChild(
1490                                parentCategory != null ? parentCategory : BudgetTreeModel.expenseCategories,
1491                                newCategory);
1492                        if (index >= 0)
1493                            treeModel.signalNodeInserted(
1494                                    path.pathByAddingChild(newCategory), index);
1495                        else
1496                            treeModel.signalStructureChanged();
1497                    }
1498                });
1499            }
1500        }
1501    
1502        /** a class that handles adding new IncomeSources */
1503        private class IncomeSourceInserter implements ActionListener
1504        {
1505    
1506            public void actionPerformed(ActionEvent e)
1507            {
1508                IncomeSourceEditor editor =
1509                        new IncomeSourceEditor(BudgetEditor.this, null);
1510                editor.addActionListener(new ActionListener()
1511                {
1512    
1513                    public void actionPerformed(ActionEvent e)
1514                    {
1515                        IncomeSourceEditor editor = (IncomeSourceEditor) (e.getSource());
1516                        assert editor.newIncomeSource != null : "null newIncomeSource";
1517                        addIncomeSource(editor.newIncomeSource);
1518                    }
1519                });
1520            }
1521        }
1522    
1523        /** a class that handles events from the registerAccount button */
1524        private class AccountInserter implements ActionListener
1525        {
1526    
1527            public void actionPerformed(ActionEvent ev)
1528            {
1529                int accountID =
1530                        AccountSelectorDialog.showDialog(BudgetEditor.this, budget, true);
1531                if (accountID < 0)
1532                    return;
1533                Account account = DataManager.getInstance().getAccount(accountID);
1534                addAccount(account);
1535            }
1536        }
1537    
1538        /* a class that handles account removal events */
1539        private class AccountRemover implements ActionListener
1540        {
1541    
1542            final Account account;
1543    
1544            AccountRemover(Account account)
1545            {
1546                this.account = account;
1547            }
1548    
1549            public void actionPerformed(ActionEvent ev)
1550            {
1551                removeAccount(account);
1552            }
1553        }
1554    }