1 package fr.ifremer.quadrige2.ui.swing.common.table.renderer;
2
3 /*-
4 * #%L
5 * Quadrige2 Core :: Quadrige2 UI Common
6 * $Id:$
7 * $HeadURL:$
8 * %%
9 * Copyright (C) 2017 Ifremer
10 * %%
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * #L%
24 */
25
26
27 import javax.swing.table.DefaultTableCellRenderer;
28 import java.util.Collection;
29
30 /**
31 * Cell renderer for collection values
32 *
33 * @author Ludovic Pecquot <ludovic.pecquot@e-is.pro>
34 * @param <T> Type of object in the collection
35 */
36 public class CollectionCellRenderer<T> extends DefaultTableCellRenderer {
37
38 private String separator = ", ";
39
40 /**
41 * <p>Constructor for CollectionCellRenderer.</p>
42 */
43 public CollectionCellRenderer() {
44 }
45
46 /**
47 * <p>Constructor for CollectionCellRenderer.</p>
48 *
49 * @param separator a {@link String} object.
50 */
51 public CollectionCellRenderer(String separator) {
52 this.separator = separator;
53 }
54
55 /**
56 * <p>getObjectString.</p>
57 *
58 * @param object a T object.
59 * @return a {@link String} object.
60 */
61 protected String getObjectString(T object) {
62 return object.toString();
63 }
64
65 /**
66 * <p>getFinalDisplayString.</p>
67 *
68 * @param text a {@link String} object.
69 * @return a {@link String} object.
70 */
71 protected String getFinalDisplayString(String text) {
72 return text;
73 }
74
75 /**
76 * <p>onParsingCollectionError.</p>
77 */
78 protected void onParsingCollectionError() {
79 throw new IllegalArgumentException("the cell content is not a Collection");
80 }
81
82 /** {@inheritDoc} */
83 @Override
84 @SuppressWarnings("unchecked")
85 protected void setValue(Object value) {
86 if (value == null) {
87 setText(null);
88 setToolTipText(null);
89 return;
90 }
91 if (value instanceof Collection) {
92 String text = "";
93 for (T object : (Collection<T>) value) {
94 text += getObjectString(object) + separator;
95 }
96 text = getFinalDisplayString(text.substring(0, text.lastIndexOf(separator)));
97 setText(text);
98 setToolTipText(text);
99 } else {
100 onParsingCollectionError();
101 }
102 }
103
104 }