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     * DateInforTablePanel.java
024     *
025     * Created on April 16, 2006, 8:46 AM
026     */
027    
028    package org.jbudget.gui.month;
029    
030    import java.awt.BorderLayout;
031    import java.awt.Color;
032    import java.awt.Component;
033    import java.awt.Font;
034    import java.awt.FontMetrics;
035    import java.awt.Point;
036    import java.awt.event.ActionEvent;
037    import java.awt.event.ActionListener;
038    import java.awt.event.MouseAdapter;
039    import java.awt.event.MouseEvent;
040    import java.util.ArrayList;
041    import java.util.List;
042    import javax.swing.JColorChooser;
043    import javax.swing.JDialog;
044    import javax.swing.JMenu;
045    import javax.swing.JMenuItem;
046    import javax.swing.JPanel;
047    import javax.swing.JPopupMenu;
048    import javax.swing.JScrollPane;
049    import javax.swing.JTable;
050    import javax.swing.ListSelectionModel;
051    import javax.swing.UIManager;
052    import javax.swing.event.CellEditorListener;
053    import javax.swing.event.ChangeEvent;
054    import javax.swing.event.ListSelectionEvent;
055    import javax.swing.event.ListSelectionListener;
056    import javax.swing.table.JTableHeader;
057    import javax.swing.table.TableCellRenderer;
058    import org.jbudget.Core.Account;
059    import org.jbudget.Core.MoneyPit;
060    import org.jbudget.Core.Month;
061    import org.jbudget.gui.GuiPreferences;
062    import org.jbudget.gui.month.renderers.DateCellRenderer;
063    import org.jbudget.io.DataManager;
064    import org.jbudget.util.Pair;
065    
066    /**
067     * A panel that contains a DatiesInfoTable.
068     *
069     * @author petrov
070     */
071    
072    public class CombinedTablePanel extends JPanel implements CellEditorListener,
073                                                        DataManager.AccountListener
074    {
075        /** The month instance that is represented by this panel */
076        private final Month month;
077        /** A table model for displaying the day of the month */
078        private final DatesTableModel datesTableModel;
079        /** A table that has a single column that shows days of the month */
080        final JTable datesTable;
081        /** A table model that is used for displaying per-day income/expense/balance 
082         */
083        private DatesInfoTableModel datesInfoTableModel;
084        /** A table that displays the income/expense/balance */
085        private final DatesInfoTable datesInfoTable;
086        private DatesInfoTable.RenderingState renderingState =
087                                    new DatesInfoTable.RenderingState();
088        public final ActionListener stateWatcher = new ActionListener()
089        {
090    
091            public void actionPerformed(ActionEvent ev)
092            {
093                initialize();
094            }
095        };
096      
097      // =========================== Constructors ===============================//
098      
099        /** Creates a new instance of DateInforTablePanel */
100        public CombinedTablePanel(Month month,
101                                   DatesInfoTableModel.State columnsState,
102                                   DatesInfoTable.RenderingState renderingState)
103        {
104            this.month = month;
105            this.renderingState = renderingState;
106            renderingState.addActionListener(stateWatcher);
107    
108            datesTableModel = new DatesTableModel(month);
109            datesTable = new JTable(datesTableModel);
110            datesTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
111            datesTable.setSelectionMode(
112                    ListSelectionModel.SINGLE_INTERVAL_SELECTION);
113            datesTable.getColumnModel().getColumn(0).setPreferredWidth(60);
114            datesTable.setGridColor(Color.BLACK);
115    
116            if (columnsState == null)
117            {
118                datesInfoTableModel = new DatesInfoTableModel(month, datesTableModel);
119            } else
120            {
121                datesInfoTableModel =
122                        new DatesInfoTableModel(month, datesTableModel, columnsState);
123            }
124    
125            datesInfoTable = new DatesInfoTable(datesInfoTableModel, renderingState);
126            datesInfoTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
127            datesInfoTable.setCellSelectionEnabled(true);
128            datesInfoTable.setSelectionMode(
129                    ListSelectionModel.SINGLE_INTERVAL_SELECTION);
130            datesInfoTable.setGridColor(Color.BLACK);
131    
132            JScrollPane scrollPane = new JScrollPane(datesInfoTable);
133            scrollPane.setRowHeaderView(datesTable);
134            scrollPane.getRowHeader().setPreferredSize(
135                    datesTable.getPreferredSize());
136            scrollPane.setCorner(JScrollPane.UPPER_LEADING_CORNER,
137                    datesTable.getTableHeader());
138            setLayout(new BorderLayout());
139            add(scrollPane, BorderLayout.CENTER);
140    
141            DataManager.getInstance().addAccountListener(this);
142    
143            updateUI();
144            initializeActions();
145            initialize();
146        }
147      
148      
149    //================================ Initializaiton ===========================//
150      
151        /** Initializes actions. */
152        private void initializeActions()
153        {
154            ListSelectionListener dateSelectionListener =
155                    new ListSelectionListener()
156                    {
157    
158                        public void valueChanged(ListSelectionEvent e)
159                        {
160                            if (e.getValueIsAdjusting())
161                            {
162                                return;
163                            }
164    
165                            int[] selectedRows = datesTable.getSelectedRows();
166                            if (selectedRows.length > 0 && datesInfoTable.getColumnCount() > 0)
167                            {
168                                datesInfoTable.setColumnSelectionInterval(
169                                        0, datesInfoTable.getColumnCount() - 1);
170                                datesInfoTable.setRowSelectionInterval(
171                                        selectedRows[0], selectedRows[selectedRows.length - 1]);
172                            }
173                        }
174                    };
175    
176            ListSelectionListener infoSelectionListener =
177                    new ListSelectionListener()
178                    {
179    
180                        public void valueChanged(ListSelectionEvent e)
181                        {
182                            if (e.getValueIsAdjusting())
183                            {
184                                datesTable.clearSelection();
185                            }
186                        }
187                    };
188    
189            datesTable.getSelectionModel().
190                    addListSelectionListener(dateSelectionListener);
191            datesInfoTable.getSelectionModel().
192                    addListSelectionListener(infoSelectionListener);
193            datesInfoTable.getColumnModel().getSelectionModel().
194                    addListSelectionListener(infoSelectionListener);
195    
196            datesInfoTable.getTableHeader().addMouseListener(new MouseAdapter()
197            {
198    
199                @Override
200                public void mousePressed(MouseEvent ev)
201                {
202                    checkPopup(ev);
203                }
204    
205                @Override
206                public void mouseReleased(MouseEvent e)
207                {
208                    checkPopup(e);
209                    if (e.getButton() == MouseEvent.BUTTON1)
210                    {
211                        int columnIndex = datesInfoTable.columnAtPoint(
212                                new Point(e.getX(), e.getY()));
213                        if (columnIndex >= datesInfoTable.getColumnCount() ||
214                                columnIndex < 0)
215                        {
216                            return;
217                        }
218                        datesTable.clearSelection();
219                        datesInfoTable.clearSelection();
220                        datesInfoTable.addRowSelectionInterval(0, datesTable.getRowCount() - 1);
221                        datesInfoTable.addColumnSelectionInterval(columnIndex, columnIndex);
222                    }
223                }
224    
225                private void checkPopup(MouseEvent ev)
226                {
227                    if (ev.isPopupTrigger())
228                    {
229                        int x = ev.getX();
230                        int y = ev.getY();
231                        JTableHeader header = datesInfoTable.getTableHeader();
232                        int columnIndex = datesInfoTable.convertColumnIndexToModel(
233                                datesInfoTable.columnAtPoint(new Point(x, y)));
234                        if (columnIndex != -1)
235                        {
236                            new ColumnMenu(columnIndex, header, x, y);
237                        }
238                    }
239                }
240            });
241        }
242    
243        private void initialize()
244        {
245            TableCellRenderer oldRenderer =
246                    datesTable.getDefaultRenderer(Integer.class);
247            DateCellRenderer renderer;
248            if (oldRenderer instanceof DateCellRenderer)
249            {
250                renderer = (DateCellRenderer) oldRenderer;
251            } else
252            {
253                renderer = new DateCellRenderer(month);
254                datesTable.setDefaultRenderer(Integer.class, renderer);
255            }
256    
257            DatesInfoTable.BackgroundType backgroundType =
258                    renderingState.getBackgroundType();
259            if (backgroundType.isStriped())
260            {
261                renderer.setPainter(renderer.new StripedPainter());
262            } else
263            {
264                renderer.setPainter(renderer.new PlainPainter());
265            }
266    
267            datesTable.repaint();
268        }
269    
270        /** Call before hiding the table */
271        public void dispose()
272        {
273            DataManager.getInstance().removeAccountListener(this);
274            datesInfoTable.dispose();
275            datesInfoTableModel.dispose();
276        }
277    
278        @Override
279        public void updateUI()
280        {
281            if (datesTable == null || datesInfoTable == null)
282            {
283                return;
284            }
285    
286            Font tableFont = UIManager.getFont(GuiPreferences.tableFontKey);
287            FontMetrics fontMetrics =
288                    CombinedTablePanel.this.getFontMetrics(tableFont);
289            int height = (int) (1.5 * fontMetrics.getStringBounds("$123",
290                    CombinedTablePanel.this.getGraphics()).getHeight());
291    
292            datesTable.setRowHeight(height);
293            datesTable.getTableHeader().setFont(tableFont.deriveFont(Font.BOLD));
294            datesInfoTable.setRowHeight(height);
295        }
296      
297      // =========================== Accessors ===================================//
298      
299        public void setRenderingState(DatesInfoTable.RenderingState renderingState)
300        {
301            this.renderingState = renderingState;
302            datesInfoTable.setRenderingState(renderingState);
303            renderingState.addActionListener(stateWatcher);
304            initialize();
305        }
306    
307        public void setColumnColors(DatesInfoTable.Colors colors)
308        {
309            datesInfoTable.setColumnColors(colors);
310        }
311    
312        /** Returns a list of selected days in the month. */
313        public List<Integer> getSelectedDays()
314        {
315            int selected[] = datesTable.getSelectedRows();
316            List<Integer> days = new ArrayList<Integer>(selected.length);
317            for (int i = 0; i < selected.length; i++)
318            {
319                days.add((Integer) datesTable.getValueAt(selected[i], 0));
320            }
321            return days;
322        }
323    
324        /** returns the table model that is used by this panel */
325        DatesInfoTableModel getTableModel()
326        {
327            return datesInfoTableModel;
328        }
329    
330        /** returns the table instance ... */
331        JTable getDatesInfoTable()
332        {
333            return datesInfoTable;
334        }
335    
336        /** returns the table instance ... */
337        JTable getDatesTable()
338        {
339            return datesTable;
340        }
341      
342      //=========================== Events =======================================//
343      
344      
345        /** Listens to changes in transactions (Should be more
346         * efficient)*/
347        public void editingStopped(ChangeEvent ev)
348        {
349            tableChanged();
350        }
351    
352        /** Listens to canceled edits */
353        public void editingCanceled(ChangeEvent ev)
354        {
355    
356        }
357    
358        /** notifies the table that something was changed and it needs to be 
359         *  redrawn.
360         */
361        public void tableChanged()
362        {
363            datesInfoTableModel.fireTableDataChanged();
364        }
365      
366      
367      // ===================== Account changes =================================//
368      
369        public void accountAdded(Account account)
370        {
371            recreateTableModel();
372        }
373    
374        public void accountRemoved(int id)
375        {
376            recreateTableModel();
377        }
378    
379        public void accountUpdated(Account account)
380        {
381            recreateTableModel();
382        }
383    
384        private void recreateTableModel()
385        {
386            DatesInfoTableModel newModel = new DatesInfoTableModel(datesInfoTableModel);
387            datesInfoTable.setModel(newModel);
388            datesInfoTableModel.dispose();
389            datesInfoTableModel = newModel;
390        }
391      
392      //============================ Inner Classes ============================//
393      
394        /** A class that creates a popup menu when a column header is right clicked.*/
395        class ColumnMenu
396        {
397    
398            private final JPopupMenu menu = new JPopupMenu();
399            private final int columnIndex;
400            private final JMenuItem hide = new JMenuItem("Hide");
401            private final JMenuItem collapse = new JMenuItem("Collapse");
402            private final JMenuItem collapseParent = new JMenuItem("Collapse Parent");
403            private final JMenuItem expand = new JMenuItem("Expand");
404            private final JMenu show = new JMenu("Show");
405            private final JMenuItem changeColor = new JMenuItem("Change Color");
406            private final JMenuItem removeColor = new JMenuItem("Remove Color");
407    
408            public ColumnMenu(int index, Component parent, int x, int y)
409            {
410                columnIndex = index;
411    
412                hide.addActionListener(new ActionListener()
413                {
414    
415                    public void actionPerformed(ActionEvent ev)
416                    {
417                        datesInfoTableModel.hideColumn(columnIndex);
418                    }
419                });
420    
421                collapse.addActionListener(new ActionListener()
422                {
423    
424                    public void actionPerformed(ActionEvent ev)
425                    {
426                        datesInfoTableModel.collapseColumn(columnIndex);
427                    }
428                });
429    
430                collapseParent.addActionListener(new ActionListener()
431                {
432    
433                    public void actionPerformed(ActionEvent ev)
434                    {
435                        datesInfoTableModel.collapseParent(columnIndex);
436                    }
437                });
438    
439                expand.addActionListener(new ActionListener()
440                {
441    
442                    public void actionPerformed(ActionEvent ev)
443                    {
444                        datesInfoTableModel.expandColumn(columnIndex);
445                    }
446                });
447    
448                changeColor.addActionListener(new ActionListener()
449                {
450    
451                    MoneyPit item = datesInfoTableModel.getItemsForColumn(columnIndex).get(0);
452                    Color c = datesInfoTable.getColumnColors().getColor(item.getContent());
453    
454                    public void actionPerformed(ActionEvent ev)
455                    {
456                        if (c == null)
457                        {
458                            c = UIManager.getColor(GuiPreferences.tableBgKey);
459                        }
460                        final JColorChooser chooser = new JColorChooser(c);
461    
462                        final JDialog dialog =
463                                JColorChooser.createDialog(CombinedTablePanel.this,
464                                "Choose Color", false, chooser,
465                                new ActionListener()
466                                {
467    
468                                    public void actionPerformed(ActionEvent ev1)
469                                    {
470                                        Color c = chooser.getColor();
471                                        datesInfoTable.getColumnColors().setColor(item.getContent(), c);
472                                    }
473                                },
474                                new ActionListener()
475                                {
476    
477                                    public void actionPerformed(ActionEvent ev1)
478                                    {
479                                    }
480                                });
481                        dialog.setVisible(true);
482                    }
483                });
484    
485                removeColor.addActionListener(new ActionListener()
486                {
487    
488                    MoneyPit item = datesInfoTableModel.getItemsForColumn(columnIndex).get(0);
489    
490                    public void actionPerformed(ActionEvent ev)
491                    {
492                        datesInfoTable.getColumnColors().setColor(item.getContent(), null);
493                    }
494                });
495    
496                menu.add(hide);
497                if (datesInfoTableModel.isCollapsable(columnIndex))
498                {
499                    menu.add(collapse);
500                }
501                if (datesInfoTableModel.isParentCollapsable(columnIndex))
502                {
503                    menu.add(collapseParent);
504                }
505                if (datesInfoTableModel.isExpandable(columnIndex))
506                {
507                    menu.add(expand);
508                }
509    
510                List<Pair<Integer, String>> hiddenAccounts =
511                        new ArrayList<Pair<Integer, String>>();
512    
513                hiddenAccounts.addAll(
514                        datesInfoTableModel.getState().getHiddenAccounts());
515    
516                List<Pair<Integer, String>> hiddenCategories =
517                        new ArrayList<Pair<Integer, String>>();
518                hiddenCategories.addAll(
519                        datesInfoTableModel.getState().getHiddenCategories());
520    
521                for (Pair<Integer, String> acctInfo : hiddenAccounts)
522                {
523                    JMenuItem item = new ShowAccountItem(acctInfo);
524                    show.add(item);
525                }
526    
527                if ((!hiddenAccounts.isEmpty()) && (!hiddenCategories.isEmpty()))
528                {
529                    show.addSeparator();
530                }
531    
532                for (Pair<Integer, String> catInfo : hiddenCategories)
533                {
534                    JMenuItem item = new ShowCategoryItem(catInfo);
535                    show.add(item);
536                }
537    
538    
539                if ((!hiddenAccounts.isEmpty()) || (!hiddenCategories.isEmpty()))
540                {
541                    menu.add(show);
542                }
543    
544                menu.addSeparator();
545                menu.add(changeColor);
546    
547    
548                MoneyPit item = datesInfoTableModel.getItemsForColumn(columnIndex).get(0);
549                Color c = datesInfoTable.getColumnColors().getColor(item.getContent());
550                if (c != null)
551                {
552                    menu.add(removeColor);
553                }
554    
555                menu.show(parent, x, y);
556            }
557    
558            class ShowAccountItem extends JMenuItem
559            {
560    
561                private final Pair<Integer, String> accountInfo;
562    
563                public ShowAccountItem(Pair<Integer, String> accountInfoArg)
564                {
565                    super(accountInfoArg.second());
566                    accountInfo = accountInfoArg;
567                    addActionListener(new ActionListener()
568                    {
569    
570                        public void actionPerformed(ActionEvent ev)
571                        {
572                            datesInfoTableModel.getState().showAccount(accountInfo);
573                        }
574                    });
575                }
576            }
577    
578            class ShowCategoryItem extends JMenuItem
579            {
580    
581                private final Pair<Integer, String> categoryInfo;
582    
583                public ShowCategoryItem(Pair<Integer, String> categoryInfoArg)
584                {
585                    super(categoryInfoArg.second());
586                    categoryInfo = categoryInfoArg;
587                    addActionListener(new ActionListener()
588                    {
589    
590                        public void actionPerformed(ActionEvent ev)
591                        {
592                            datesInfoTableModel.getState().showCategory(categoryInfo);
593                        }
594                    });
595                }
596            }
597        }
598    }