web lib: getStory
[fanfix.git] / src / be / nikiroo / jexer / TTableColumn.java
CommitLineData
8f34a795
NR
1package be.nikiroo.jexer;
2
3import javax.swing.table.TableModel;
4
5import be.nikiroo.jexer.TTableCellRenderer.CellRendererMode;
6
7public class TTableColumn {
8 static private TTableCellRenderer defaultrenderer = new TTableCellRendererText(
9 CellRendererMode.NORMAL);
10
11 private TableModel model;
12 private int modelIndex;
13 private int width;
14 private boolean forcedWidth;
15
16 private TTableCellRenderer renderer;
17
18 /** The auto-computed width of the column (the width of the largest value) */
19 private int autoWidth;
20
21 private Object headerValue;
22
23 public TTableColumn(int modelIndex) {
24 this(modelIndex, null);
25 }
26
27 public TTableColumn(int modelIndex, String colName) {
28 this(modelIndex, colName, null);
29 }
30
31 // set the width and preferred with the the max data size
32 public TTableColumn(int modelIndex, Object colValue, TableModel model) {
33 this.model = model;
34 this.modelIndex = modelIndex;
35
36 reflowData();
37
38 if (colValue != null) {
39 setHeaderValue(colValue);
40 }
41 }
42
43 // never null
44 public TTableCellRenderer getRenderer() {
45 return renderer != null ? renderer : defaultrenderer;
46 }
47
48 public void setCellRenderer(TTableCellRenderer renderer) {
49 this.renderer = renderer;
50 }
51
52 /**
53 * Recompute whatever data is displayed by this widget.
54 * <p>
55 * Will just update the sizes in this case.
56 */
57 public void reflowData() {
58 if (model != null) {
59 int maxDataSize = 0;
60 for (int i = 0; i < model.getRowCount(); i++) {
61 maxDataSize = Math.max(
62 maxDataSize,
63 getRenderer().getWidthOf(
64 model.getValueAt(i, modelIndex)));
65 }
66
67 autoWidth = maxDataSize;
68 if (!forcedWidth) {
69 setWidth(maxDataSize);
70 }
71 } else {
72 autoWidth = 0;
73 forcedWidth = false;
74 width = 0;
75 }
76 }
77
78 public int getModelIndex() {
79 return modelIndex;
80 }
81
82 /**
83 * The actual size of the column. This can be auto-computed in some cases.
84 *
85 * @return the width (never &lt; 0)
86 */
87 public int getWidth() {
88 return width;
89 }
90
91 /**
92 * Set the actual size of the column or -1 for auto size.
93 *
94 * @param width
95 * the width (or -1 for auto)
96 */
97 public void setWidth(int width) {
98 forcedWidth = width >= 0;
99
100 if (forcedWidth) {
101 this.width = width;
102 } else {
103 this.width = autoWidth;
104 }
105 }
106
107 /**
108 * The width was forced by the user (using
109 * {@link TTableColumn#setWidth(int)} with a positive value).
110 *
111 * @return TRUE if it was
112 */
113 public boolean isForcedWidth() {
114 return forcedWidth;
115 }
116
117 // not an actual forced width, but does change the width return
118 void expandWidthTo(int width) {
119 this.width = width;
120 }
121
122 public Object getHeaderValue() {
123 return headerValue;
124 }
125
126 public void setHeaderValue(Object headerValue) {
127 this.headerValue = headerValue;
128 }
129}