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     * AccountSelectorPanel.java
024     *
025     * Created on July 20, 2006, 5:30 PM
026     */
027    
028    package org.jbudget.gui.budget;
029    
030    import java.awt.BorderLayout;
031    import java.awt.Color;
032    import java.awt.Component;
033    import java.awt.Dimension;
034    import java.awt.Font;
035    import java.awt.FontMetrics;
036    import java.awt.Graphics;
037    import java.awt.geom.Rectangle2D;
038    import java.util.LinkedList;
039    import java.util.List;
040    import javax.swing.Icon;
041    import javax.swing.JLabel;
042    import javax.swing.JPanel;
043    import javax.swing.JScrollPane;
044    import javax.swing.JTable;
045    import javax.swing.ListSelectionModel;
046    import javax.swing.UIManager;
047    import javax.swing.event.ListSelectionEvent;
048    import javax.swing.event.ListSelectionListener;
049    import javax.swing.table.TableCellRenderer;
050    import javax.swing.table.TableColumn;
051    import javax.swing.table.TableModel;
052    import org.jbudget.Core.Budget;
053    import org.jbudget.Core.User;
054    import org.jbudget.gui.GuiPreferences;
055    
056    /**
057     * A JPanel containing a list of accounts one of which can be selected.
058     * @author petrov
059     */
060    public class AccountSelectorPanel extends JPanel
061    {
062      private final AccountSelectorModel model;
063      private final JTable accountListTable;
064      
065      /** Holds id of the selected budget */
066      private int selectedAccountID = -1;
067      
068      /** A list of components that are notified about changes in account selection
069       */
070      private List<AccountSelectionListener> listeners = 
071          new LinkedList<AccountSelectionListener>();
072      
073      HoldersRenderer holdersRenderer = new HoldersRenderer();
074      IdRenderer idRenderer = new IdRenderer();
075      NameRenderer nameRenderer = new NameRenderer();
076          
077      /** Creates a new instance of AccountSelectorPanel.
078       * @param showUnused if true only account that are not registered with
079       *        any budget are shown. In the opposite case all account are shown.
080       */
081      public AccountSelectorPanel(boolean showUnused)
082      {
083        super();
084        model = new AccountSelectorModel(showUnused);
085        accountListTable = new JTable(model);
086        accountListTable.setTableHeader(null);
087        accountListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
088        accountListTable.setShowGrid(false);
089        
090        accountListTable.getColumnModel(
091            ).getColumn(2).setCellRenderer(holdersRenderer);
092        accountListTable.getColumnModel(
093            ).getColumn(1).setCellRenderer(idRenderer);
094        accountListTable.getColumnModel(
095            ).getColumn(0).setCellRenderer(nameRenderer);
096        
097        accountListTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
098        
099        setLayout(new BorderLayout());
100        add(new JScrollPane(accountListTable), BorderLayout.CENTER);
101        
102        initActions();
103      }
104      
105      /** Shows all accounts. */
106      public AccountSelectorPanel()
107      {
108        this(false);
109      }
110      
111      /** Shows accounts registered with a budget or all accounts that are not
112       *  registered with a budget.
113       *  @param showUnregistered if true, the list will show only accounts that
114       *         were not registered with the budget.
115       */
116      public AccountSelectorPanel(Budget budget, boolean showUnregistered)
117      {
118        super();
119        model = new AccountSelectorModel(budget, showUnregistered);
120        accountListTable = new JTable(model);
121        accountListTable.setTableHeader(null);
122        accountListTable.setShowGrid(false);
123        
124        accountListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
125        accountListTable.getColumnModel(
126            ).getColumn(2).setCellRenderer(holdersRenderer);
127        accountListTable.getColumnModel(
128            ).getColumn(1).setCellRenderer(idRenderer);
129        accountListTable.getColumnModel(
130            ).getColumn(0).setCellRenderer(nameRenderer);
131        
132        accountListTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
133        
134        setLayout(new BorderLayout());
135        add(new JScrollPane(accountListTable), BorderLayout.CENTER);
136        
137        initActions();
138      }
139      
140      /** Shows accounts registered with a budget. */
141      public AccountSelectorPanel(Budget budget)
142      {
143        this(budget, false);
144      }
145      
146      /** resizing */
147      public void validate()
148      {
149        super.validate();
150        Dimension dim = getSize();
151        int width = (int)dim.getWidth();
152        int height = (int)dim.getHeight();
153        width -= 4;
154        height -= 4;
155        accountListTable.setPreferredSize(new Dimension(width, height));
156        updateSizes(getGraphics(), accountListTable);
157      }
158      
159      /** Initializes gui actions */
160      private void initActions()
161      {
162        accountListTable.getSelectionModel().addListSelectionListener(
163            new ListSelectionListener(){
164              public void valueChanged(ListSelectionEvent e){
165                int rowIndex = accountListTable.getSelectedRow();
166                if (rowIndex == -1)
167                  return;
168                selectedAccountID = 
169                    ((Integer)model.getValueAt(rowIndex,1)).intValue();
170                notifyListeners();
171          }
172        });
173      }
174      
175      /** Frees resources. Must be called before closing the widget. */
176      public void dispose(){
177        model.dispose();
178      }
179      
180      /** Returns the ID of currently selected budget; -1 if no budget is selected. */
181      public int getSelectedAccountID(){
182        return selectedAccountID;
183      }
184      
185      /** Updates the widths and heights of the cells to accomodate the contents. */
186      public static void updateSizes(Graphics g, JTable table)
187      {
188        FontMetrics metrics = table.getFontMetrics(table.getFont());
189        TableModel model = table.getModel();
190        int nColumns = model.getColumnCount();
191        int nRows = model.getRowCount();
192        
193        Dimension dim = table.getPreferredSize();
194        int tableWidth = (int)dim.getWidth();
195        int defaultWidth = tableWidth/nColumns;
196        int defaultHeight = 20;
197        int runningWidth = 0;
198        
199        if (g != null)
200        {
201          int h = 0;
202          for (int column = 0; column < nColumns; column++)
203          {
204            TableColumn columnObj = table.getColumnModel().getColumn(column);
205            TableCellRenderer renderer = columnObj.getCellRenderer();
206            int w = 0;
207            for (int row = 0; row < nRows; row ++)
208            {
209              Component c = renderer.getTableCellRendererComponent(table,
210                          model.getValueAt(row,column), false, false, row, column);
211              int currWidth;
212              int currHeight;
213              if (c instanceof JLabel)
214              {
215                JLabel label = (JLabel)c;
216                String str = label.getText();
217                Icon icon = label.getIcon();
218                
219                int iconW = 0;
220                int iconH = 0;
221                
222                if (icon != null)
223                {
224                  iconW = icon.getIconWidth();
225                  iconH = icon.getIconHeight();
226                }
227                
228                int strW = 0;
229                int strH = 0;
230                
231                if (str != null)
232                {
233                  Rectangle2D rect = metrics.getStringBounds(str, g);
234                  strW = (int)rect.getWidth();
235                  strH = (int)rect.getHeight();
236                }
237                
238                currWidth = iconW + strW + 10;
239                currHeight = iconH > strH ? iconH : strH;
240                currHeight += 4;
241              }
242              else
243              {
244                currWidth = defaultWidth;
245                currHeight = defaultHeight;
246              }
247              if (currHeight > h)
248                h = currHeight;
249              if (currWidth > w)
250                w = currWidth;
251            }
252            runningWidth += w;
253            if (column == nColumns - 1)
254            {  
255              if (runningWidth < tableWidth)
256                w += tableWidth - runningWidth;
257              else
258              {
259                int ht = (int)table.getPreferredSize().getHeight();
260                Dimension size = new Dimension(runningWidth, ht);
261                table.setPreferredSize(size);
262              }
263            }
264              
265            columnObj.setPreferredWidth(w);
266            columnObj.setWidth(w);
267          }
268          table.setRowHeight(h);
269          Dimension size = table.getPreferredSize();
270          int height = (int)size.getHeight();
271          if (height < h * nRows)
272          {
273            int width = (int)size.getWidth();
274            table.setPreferredSize(new Dimension(width, h * nRows));
275          }
276        }
277        else
278        {
279          for (int column = 0; column < nColumns; column++)
280          {
281            TableColumn columnObj = table.getColumnModel().getColumn(column);
282            columnObj.setPreferredWidth(defaultWidth);
283            columnObj.setWidth(defaultWidth);
284          }
285          table.setRowHeight(defaultHeight);
286        }
287        
288        table.doLayout();
289      }
290      
291      //================== Working with budget selection listeners =============//
292      
293      public void addListener(AccountSelectionListener listener){
294        listeners.add(listener);
295      }
296      
297      public void removeListener(AccountSelectionListener listener){
298        listeners.remove(listener);
299      }
300      
301      public void notifyListeners(){
302        for (AccountSelectionListener listener : listeners)
303          listener.accountSelected(selectedAccountID);
304      }
305      
306      //================== Inner classes and interfaces =======================//
307      
308      public static interface AccountSelectionListener {
309        public void accountSelected(int accountID);
310      }
311      
312      public static class RendererBase extends JLabel
313      {
314        protected Color bgColor1;
315        protected Color bgColor2;
316        protected Color fgColor;
317        protected Color sBgColor;
318        protected Color sFgColor;
319      
320        protected Font font;
321        protected Icon accountIcon;
322        
323        protected boolean wasSelected = true;
324        
325        public RendererBase(){
326          setOpaque(true);
327          updateUI();
328        }
329        
330        protected void setupColors(boolean isSelected, int row)
331        {
332          if (isSelected)
333          {
334            wasSelected = true;
335            setBackground(sBgColor);
336            setForeground(sFgColor);
337          }
338          else
339          {
340            if (row%2 == 1)
341              setBackground(bgColor2);
342            else
343              setBackground(bgColor1);
344            if (wasSelected)
345              setForeground(fgColor);
346          }
347        }
348        
349        public void updateUI()
350        {
351            super.updateUI();
352            
353            font = UIManager.getFont(GuiPreferences.tableFontKey);
354            bgColor1 = UIManager.getColor(GuiPreferences.tableBgKey);
355            bgColor2 = UIManager.getColor(GuiPreferences.tableAltBgKey);
356            fgColor = UIManager.getColor(GuiPreferences.tableFgKey);
357            sBgColor = UIManager.getColor(GuiPreferences.tableSelectionBgKey);
358            sFgColor = UIManager.getColor(GuiPreferences.tableSelectionFgKey);
359    
360            setFont(font);
361    
362            accountIcon = UIManager.getIcon(GuiPreferences.iconAccountKey);
363        }
364      }
365      
366      public static class HoldersRenderer extends RendererBase
367                                          implements TableCellRenderer 
368      {
369           
370        public Component  getTableCellRendererComponent(
371                                     JTable table, Object value, boolean isSelected, 
372                                     boolean hasFocus, int row, int column) 
373        {
374          setupColors(isSelected, row);
375          List<User> users = (List<User>)value;
376    
377          StringBuffer holders = new StringBuffer();
378          holders.append("[");
379          if (users.size() == 0)
380            holders.append("none");
381          else
382          {
383            boolean first = true;
384            for (User u : users)
385            {
386              if (!first)
387                holders.append(", ");
388              else 
389                first = false;
390              holders.append(u.getName());
391            }
392          }
393          holders.append("]");
394    
395          setText(holders.toString());
396          return this;
397        }
398      }
399      
400      public static class IdRenderer extends RendererBase
401                                     implements TableCellRenderer 
402      {
403        public Component  getTableCellRendererComponent(
404                                     JTable table, Object value, boolean isSelected, 
405                                     boolean hasFocus, int row, int column) 
406        {
407          setupColors(isSelected, row);
408          
409          Integer id = (Integer)value;
410          setText("ID: " + id.toString());
411          return this;
412        }
413      }
414      
415      public static class NameRenderer extends RendererBase
416                                     implements TableCellRenderer 
417      {
418        public NameRenderer() {
419          setIcon(accountIcon);
420        }
421        
422        protected void initialize()
423        {
424          setIcon(accountIcon);
425        }
426        
427        public Component  getTableCellRendererComponent(
428                                     JTable table, Object value, boolean isSelected, 
429                                     boolean hasFocus, int row, int column) 
430        {
431          setupColors(isSelected, row);
432          
433          setText((String)value);
434          return this;
435        }
436      }
437    }