1 package fr.ifremer.quadrige3.ui.swing.table.renderer;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import org.apache.commons.lang3.StringUtils;
28
29 import javax.swing.*;
30 import javax.swing.table.TableCellRenderer;
31 import java.awt.Color;
32 import java.awt.Component;
33 import java.awt.Font;
34
35
36
37
38
39
40
41 public class ButtonCellRenderer<T> implements TableCellRenderer {
42
43 private final boolean hideValue;
44
45 private Font defaultFont;
46
47 private Font selectedFont;
48
49 protected final Icon icon;
50
51
52
53
54 public ButtonCellRenderer() {
55 this(null, false);
56 }
57
58
59
60
61
62
63 public ButtonCellRenderer(boolean hideValue) {
64 this(null, hideValue);
65 }
66
67
68
69
70
71
72
73 public ButtonCellRenderer(Icon icon, boolean hideValue) {
74 this.icon = icon;
75 this.hideValue = hideValue;
76 }
77
78
79 @Override
80 @SuppressWarnings("unchecked")
81 public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
82
83 JButton button = new JButton();
84
85 button.setBackground(null);
86 button.setForeground(Color.BLACK);
87 button.setHorizontalAlignment(SwingConstants.CENTER);
88
89 T object = (T) value;
90
91 if (hideValue) {
92 button.setText(null);
93 } else {
94 String text = getText(table, object, row, column);
95 button.setText(text != null ? text : value.toString());
96 }
97 Icon icon = getIcon(table, object, row, column);
98 if (icon != null) {
99 button.setIcon(icon);
100 }
101 String toolTipText = getToolTipText(table, object, row, column);
102 if (StringUtils.isNotBlank(toolTipText)) {
103 button.setToolTipText(toolTipText);
104 }
105
106 boolean editable = table.isCellEditable(row, column);
107 button.setEnabled(editable);
108
109 if (defaultFont == null) {
110 defaultFont = UIManager.getFont("Table.font");
111 selectedFont = defaultFont.deriveFont(Font.BOLD);
112 }
113
114 if (isSelected) {
115 button.setFont(selectedFont);
116 } else {
117 button.setFont(defaultFont);
118 }
119
120 return button;
121 }
122
123
124
125
126
127
128
129
130
131
132 protected String getText(JTable table, T value, int row, int column) {
133 return null;
134 }
135
136
137
138
139
140
141
142
143
144
145 protected Icon getIcon(JTable table, T value, int row, int column) {
146 return this.icon;
147 }
148
149
150
151
152
153
154
155
156
157
158 protected String getToolTipText(JTable table, T value, int row, int column) {
159 return null;
160 }
161 }