1
2
3
4 package ca.spaz.cron.ui;
5
6 import java.util.List;
7
8 import javax.swing.table.AbstractTableModel;
9
10 import ca.spaz.cron.database.*;
11
12 public class NutrientTableModel extends AbstractTableModel {
13
14 private static final int NAME_COLUMN = 0;
15 private static final int AMOUNT_COLUMN = 1;
16 private static final int UNIT_COLUMN = 2;
17 private static final int RDI_COLUMN = 3;
18
19 private String[] columnNames = { "Nutrient", "Amount", "Units", "%DV" };
20
21 List nutrients;
22
23 private Food food;
24 private double multiplier = 1;
25
26 public NutrientTableModel(List nutrientInfo) {
27 this.nutrients = nutrientInfo;
28 }
29
30 public void setMultiplier(double val) {
31 this.multiplier = val;
32 fireTableDataChanged();
33 }
34
35 public void setFood(Food f) {
36 this.food = f;
37 }
38
39 public Class getColumnClass(int col) {
40 Object o = getValueAt(0, col);
41 if (o != null) {
42 return o.getClass();
43 }
44 return String.class;
45 }
46
47 public int getColumnCount() {
48 return columnNames.length;
49 }
50
51 public String getColumnName(int col) {
52 return columnNames[col].toString();
53 }
54
55 public NutrientInfo getNutrientInfo(int i) {
56 return (NutrientInfo) nutrients.get(i);
57 }
58
59 public int getRowCount() {
60 return nutrients.size();
61 }
62 public Object getValueAt(int row, int col) {
63 NutrientInfo ni = getNutrientInfo(row);
64 if (ni != null) {
65 double val = multiplier * food.getNutrientAmount(ni);
66 switch (col) {
67 case NAME_COLUMN:
68 return ni.getName();
69 case AMOUNT_COLUMN:
70 val = Math.round(100000 * val) / 100000.0;
71 return new Double(val);
72 case UNIT_COLUMN:
73 return ni.getUnits();
74 case RDI_COLUMN:
75 double RDI = ni.getReferenceDailyIntake();
76 if (RDI > 0) {
77 return new Integer((int)(100*val/RDI));
78 }
79 return null;
80 }
81 }
82 return "";
83 }
84
85 public boolean isCellEditable(int row, int col) {
86 NutrientInfo ni = getNutrientInfo(row);
87 if (food != null && ni != null) {
88 if (col == AMOUNT_COLUMN) {
89 return true;
90 }
91 if (col == RDI_COLUMN) {
92 if (ni.getReferenceDailyIntake() > 0) {
93 return true;
94 }
95 }
96 }
97 return false;
98 }
99
100 public void setValueAt(Object value, int row, int col) {
101 if (col == AMOUNT_COLUMN && value != null) {
102 NutrientInfo ni = getNutrientInfo(row);
103 if (ni != null) {
104 double val = ((Double) value).doubleValue();
105 food.setNutrientAmount(ni, val / multiplier);
106 fireTableRowsUpdated(row, row);
107 }
108 }
109
110 if (col == RDI_COLUMN && value != null) {
111 NutrientInfo ni = getNutrientInfo(row);
112 if (ni != null) {
113 double val = ((Integer) value).intValue();
114 double RDI = ni.getReferenceDailyIntake();
115 val = (val/100.0) * RDI;
116 food.setNutrientAmount(ni, val / multiplier);
117 fireTableRowsUpdated(row, row);
118 }
119 }
120 }
121
122 }