You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GenericTableModel.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.addons.ui_swing.components;
  18. import com.dmdirc.util.functional.TriConsumer;
  19. import java.lang.reflect.Method;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.Collections;
  23. import java.util.List;
  24. import java.util.Optional;
  25. import java.util.function.BiFunction;
  26. import javax.swing.table.AbstractTableModel;
  27. import static com.google.common.base.Preconditions.checkArgument;
  28. import static com.google.common.base.Preconditions.checkElementIndex;
  29. import static com.google.common.base.Preconditions.checkNotNull;
  30. /**
  31. * Table model that display fields from a type of object.
  32. *
  33. * @param <T> Type of object to display
  34. */
  35. public class GenericTableModel<T> extends AbstractTableModel {
  36. /**
  37. * Serialisation version.
  38. */
  39. private static final long serialVersionUID = 1L;
  40. /**
  41. * List of values in the model.
  42. */
  43. private final List<T> values;
  44. /**
  45. * List of getters for each value, used as columns.
  46. */
  47. private final Method[] getters;
  48. /**
  49. * List of header names for each column.
  50. */
  51. private final String[] headers;
  52. /**
  53. * Generic type this table contains, used to verify getters exist.
  54. */
  55. private final Class<T> type;
  56. /**
  57. * Cached return types for the getters.
  58. */
  59. private final Class<?>[] columnTypes;
  60. private final BiFunction<Integer, Integer, Boolean> isEditable;
  61. private final TriConsumer<Object, Integer, Integer> editFunction;
  62. /**
  63. * Creates a new generic table model.
  64. *
  65. * @param type Type to be displayed, used to verify getters
  66. * @param getterValues Names of the getters to display in the table
  67. */
  68. public GenericTableModel(final Class<T> type, final String... getterValues) {
  69. this(type, (row, column) -> false, (value, row, column) -> {}, getterValues);
  70. }
  71. /**
  72. * Creates a new generic table model.
  73. *
  74. * @param type Type to be displayed, used to verify getters
  75. * @param isEditable Function to decide if a cell is editable or not
  76. * First parameter is the row
  77. * Second parameter is the column
  78. * Third parameter is the return type
  79. * @param editFunction The function to be called when editing a particular cell.
  80. * First parameter is the object
  81. * Second parameter is the row
  82. * Third parameter is the column
  83. * @param getterValues Names of the getters to display in the table
  84. */
  85. public GenericTableModel(final Class<T> type,
  86. final BiFunction<Integer, Integer, Boolean> isEditable,
  87. final TriConsumer<Object, Integer, Integer> editFunction,
  88. final String... getterValues) {
  89. checkArgument(getterValues.length > 0, "Getters must be set");
  90. checkNotNull(isEditable);
  91. checkNotNull(editFunction);
  92. this.isEditable = isEditable;
  93. this.editFunction = editFunction;
  94. this.type = type;
  95. values = new ArrayList<>();
  96. headers = new String[getterValues.length];
  97. getters = new Method[getterValues.length];
  98. columnTypes = new Class<?>[getterValues.length];
  99. for (int i = 0; i < getterValues.length; i++) {
  100. final String getterName = getterValues[i];
  101. checkNotNull(getterName, "Getter must not be null");
  102. checkArgument(!getterName.isEmpty(), "Getter must not be empty");
  103. final Optional<Method> method = getGetter(getterName);
  104. checkArgument(method.isPresent(), "Getter must exist in type");
  105. getters[i] = method.get();
  106. headers[i] = getterValues[i];
  107. columnTypes[i] = getGetter(getterValues[i]).get().getReturnType();
  108. }
  109. }
  110. @Override
  111. public int getRowCount() {
  112. return values.size();
  113. }
  114. @Override
  115. public int getColumnCount() {
  116. return getters.length;
  117. }
  118. @Override
  119. public String getColumnName(final int column) {
  120. checkElementIndex(column, headers.length, "Column must exist");
  121. return headers[column];
  122. }
  123. @Override
  124. public Class<?> getColumnClass(final int columnIndex) {
  125. checkElementIndex(columnIndex, getters.length, "Column must exist");
  126. return columnTypes[columnIndex];
  127. }
  128. @Override
  129. public Object getValueAt(final int rowIndex, final int columnIndex) {
  130. checkElementIndex(rowIndex, values.size(), "Row index must exist");
  131. checkElementIndex(columnIndex, getters.length, "Column index must exist");
  132. try {
  133. final T value = values.get(rowIndex);
  134. return getters[columnIndex].invoke(value);
  135. } catch (IndexOutOfBoundsException | ReflectiveOperationException ex) {
  136. return ex.getMessage();
  137. }
  138. }
  139. @Override
  140. public boolean isCellEditable(final int rowIndex, final int columnIndex) {
  141. return isEditable.apply(rowIndex, columnIndex);
  142. }
  143. /**
  144. * Returns the value at the specified row.
  145. *
  146. * @param rowIndex Index to retrieve
  147. *
  148. * @return Value at the specified row
  149. */
  150. public T getValue(final int rowIndex) {
  151. checkElementIndex(rowIndex, values.size(), "Row index must exist");
  152. return values.get(rowIndex);
  153. }
  154. /**
  155. * Returns the index of the specified object, or -1 if the object does not exist.
  156. *
  157. * @param object Object to find
  158. *
  159. * @return Item index, or -1 if it did not exist
  160. */
  161. public int getIndex(final T object) {
  162. return values.indexOf(object);
  163. }
  164. /**
  165. * Sets all of the header names. Must include all the headers.
  166. *
  167. * @param headerValues Names for all headers in the table
  168. */
  169. public void setHeaderNames(final String... headerValues) {
  170. checkArgument(headerValues.length == getters.length,
  171. "There must be as many headers as columns");
  172. System.arraycopy(headerValues, 0, headers, 0, headerValues.length);
  173. fireTableStructureChanged();
  174. }
  175. /**
  176. * Adds the specified value at the specified index, the column is ignored.
  177. *
  178. * @param value Value to add
  179. * @param rowIndex Index of the row to add
  180. * @param columnIndex This is ignored
  181. */
  182. @Override
  183. public void setValueAt(final Object value, final int rowIndex, final int columnIndex) {
  184. checkElementIndex(rowIndex, values.size(), "Row index must exist");
  185. checkElementIndex(columnIndex, getters.length, "Column index must exist");
  186. try {
  187. editFunction.accept(value, rowIndex, columnIndex);
  188. fireTableRowsUpdated(rowIndex, rowIndex);
  189. } catch (ClassCastException ex) {
  190. throw new IllegalArgumentException("Value of incorrect type.", ex);
  191. }
  192. }
  193. /**
  194. * Replaces the value at the specified index with the specified value.
  195. *
  196. * @param value New value to insert
  197. * @param rowIndex Index to replace
  198. */
  199. public void replaceValueAt(final T value, final int rowIndex) {
  200. checkNotNull(value, "Value must not be null");
  201. checkElementIndex(rowIndex, values.size(), "RowIndex must be valid");
  202. values.set(rowIndex, value);
  203. fireTableRowsUpdated(rowIndex, rowIndex);
  204. }
  205. /**
  206. * Removes a value from the model.
  207. *
  208. * @param value Value to be removed.
  209. */
  210. public void removeValue(final T value) {
  211. checkArgument(values.contains(value), "Value must exist");
  212. final int index = values.indexOf(value);
  213. values.remove(value);
  214. fireTableRowsDeleted(index, index);
  215. }
  216. /**
  217. * Removes all the values from the model.
  218. */
  219. public void removeAll() {
  220. values.clear();
  221. fireTableDataChanged();
  222. }
  223. /**
  224. * Adds the specified value at the end of the model.
  225. *
  226. * @param value Value to add
  227. */
  228. public void addValue(final T value) {
  229. values.add(value);
  230. final int index = values.indexOf(value);
  231. fireTableRowsInserted(index, index);
  232. }
  233. /**
  234. * Returns a collection of all the elements in this model.
  235. *
  236. * @return All elements in the model
  237. */
  238. public Collection<T> elements() {
  239. return Collections.unmodifiableCollection(values);
  240. }
  241. /**
  242. * Returns an optional method for the specified name.
  243. *
  244. * @param name Name of the getter
  245. *
  246. * @return Optional method
  247. */
  248. private Optional<Method> getGetter(final String name) {
  249. try {
  250. return Optional.ofNullable(type.getMethod(name));
  251. } catch (NoSuchMethodException ex) {
  252. return Optional.empty();
  253. }
  254. }
  255. }