summaryrefslogtreecommitdiff
path: root/projects/net.wotonomy.ui.swing/src/main/java/net/wotonomy/ui/swing/components/KeyableCellEditor.java
blob: f64e607b86674c61cfb50df208a3e5ff6637afbe (plain)
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
Wotonomy: OpenStep design patterns for pure Java applications.
Copyright (C) 2000 Blacksmith, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see http://www.gnu.org
*/

package net.wotonomy.ui.swing.components;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.Serializable;
import java.text.Format;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;

/**
 * A table cell editor customized for keyboard navigation, much like working
 * with a spreadsheet. The default cell editor unfortunately does none of these
 * things:
 * <ul>
 * <li>Selects text on start of editing.
 * <li>Up and down keys move edit cell up and down.
 * <li>Right and left keys move cell when selection caret is at end of text.
 * <li>Escape cancels editing.
 * <li>Enter commits edit.
 * <li>Edits are properly committed on lost focus.
 * <li>Tab and shift-tab work as expected.
 * <li>Cell selection moves with the edit cell.
 * </ul>
 *
 * @author michael@mpowers.net
 * @author $Author: cgruber $
 * @version $Revision: 904 $ $Date: 2006-02-18 18:19:05 -0500 (Sat, 18 Feb 2006)
 *          $
 */
public class KeyableCellEditor implements TableCellEditor, FocusListener, KeyListener, Serializable {
	List listeners;
	JTextField textField;
	Object lastValue;
	Format currentFormat;

	JTable table;

	/**
	 * Default constructor - a standard JTextField will be used for editing.
	 */
	public KeyableCellEditor() {
		this((JTextField) null);
	}

	/**
	 * Constructor specifying a type of JTextField to be used for editing. The
	 * JTextField will have its border replaced with a black line border.
	 * 
	 * @param aTextField A JTextField or subclass for editing values.
	 */
	public KeyableCellEditor(JTextField aTextField) {
		listeners = new Vector();
		lastValue = null;

		// default to stock JTextField
		textField = aTextField;
		if (textField == null) {
			textField = new JTextField();
		}

		textField.setBorder(new LineBorder(Color.black));

		// handle arrow keys while caret is showing
		textField.addKeyListener(this);

		// handle lost focus
		textField.addFocusListener(this);
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		this.table = table;
		table.removeKeyListener(this); // if any
		table.addKeyListener(this);
		return getEditorComponent(value);
	}

	protected Component getEditorComponent(Object value) {
		if (value != null) {
			textField.setText(value.toString());
		} else {
			textField.setText("");
		}

		if (value instanceof Number) {
			textField.setHorizontalAlignment(JTextField.RIGHT);
		} else {
			textField.setHorizontalAlignment(JTextField.LEFT);
		}

		// remember original value
		lastValue = value;

		// select all text and get focus
		textField.selectAll();
		textField.requestFocus();

		return textField;
	}

	public Object getCellEditorValue() {
		return lastValue;
	}

	public boolean isCellEditable(EventObject anEvent) {
		// key events should replace the selection
		// NOTE: For whatever reason, key events trigger result in a null parameter
		if (anEvent == null) {
			textField.setText("");
			textField.requestFocus();
			return true;
		}

		return true;
	}

	public boolean shouldSelectCell(EventObject anEvent) { // System.out.println( "KeyableCellEditor.shouldSelectCell: "
															// + anEvent );

		// key events should replace the selection
		// NOTE: For whatever reason, key events are not generated
		if (anEvent instanceof KeyEvent) {
			textField.setText("");
			textField.requestFocus();
			return true;
		}

		// otherwise, select all text and continue
		textField.selectAll();
		textField.requestFocus();

		return true;
	}

	public boolean stopCellEditing() {
		lastValue = textField.getText();
		fireEditingStopped();
		table.removeKeyListener(this); // if any
		return true;
	}

	public void cancelCellEditing() {
		fireEditingCanceled();
		table.removeKeyListener(this); // if any
	}

	public void addCellEditorListener(CellEditorListener l) {
		listeners.add(l);
	}

	public void removeCellEditorListener(CellEditorListener l) {
		listeners.remove(l);
	}

	protected void fireEditingCanceled() {
		ChangeEvent event = new ChangeEvent(this);
		Iterator it = new ArrayList(listeners).iterator(); // copy to prevent modification exception
		while (it.hasNext()) {
			((CellEditorListener) it.next()).editingCanceled(event);
		}
	}

	protected void fireEditingStopped() {
		ChangeEvent event = new ChangeEvent(this);
		Iterator it = new ArrayList(listeners).iterator(); // copy to prevent modification exception
		while (it.hasNext()) {
			((CellEditorListener) it.next()).editingStopped(event);
		}
	}

	protected void onEnterKey() {
		stopCellEditing();
	}

	protected void onEscapeKey() {
		cancelCellEditing();
	}

	protected void moveEditCell(int dRow, int dCol) {
		if (table == null)
			return;
		int row = table.getSelectedRow() + dRow;
		int col = table.getSelectedColumn() + dCol;

		row = Math.max(0, row);
		row = Math.min(row, table.getRowCount() - 1);
		col = Math.max(0, col);
		col = Math.min(col, table.getColumnCount() - 1);

		stopCellEditing();
		table.setRowSelectionInterval(row, row);
		table.setColumnSelectionInterval(col, col);
		table.editCellAt(row, col);
		textField.selectAll();
		textField.requestFocus();
	}

	// interface KeyListener

	public void keyTyped(KeyEvent e) { // System.out.println( "KeyableCellEditor.keyTyped: " + KeyEvent.getKeyText(
										// e.getKeyCode() ) );
	}

	public void keyPressed(KeyEvent e) { // System.out.println( "KeyableCellEditor.keyPressed: " + KeyEvent.getKeyText(
											// e.getKeyCode() ) );

		// catch LEFT and RIGHT here before JTextField consumes them

		int keyCode = e.getKeyCode();
		if (keyCode == KeyEvent.VK_LEFT) {
			if (textField.getSelectionStart() == 0) {
				moveEditCell(0, -1);
				e.consume();
				return;
			}
		}
		if (keyCode == KeyEvent.VK_RIGHT) {
			if (textField.getSelectionEnd() == textField.getText().length()) {
				moveEditCell(0, 1);
				e.consume();
				return;
			}
		}
		if (keyCode == KeyEvent.VK_UP) {
			moveEditCell(-1, 0);
			e.consume();
			return;
		}
		if (keyCode == KeyEvent.VK_DOWN) {
			moveEditCell(1, 0);
			e.consume();
			return;
		}
	}

	public void keyReleased(KeyEvent e) { // System.out.println( "KeyableCellEditor.keyReleased: " +
											// KeyEvent.getKeyText( e.getKeyCode() ) );

		// catch ENTER here to allow JTextField to process it as well

		int keyCode = e.getKeyCode();
		if (keyCode == KeyEvent.VK_ENTER) {
			onEnterKey();
			return;
		}
		if (keyCode == KeyEvent.VK_ESCAPE) {
			onEscapeKey();
			return;
		}

		// tabs are apparently only received on key release
		if (keyCode == KeyEvent.VK_TAB) {
			if (e.isShiftDown()) {
				moveEditCell(0, -1);
			} else {
				moveEditCell(0, 1);
			}
			e.consume();
			return;
		}

	}

	// interface FocusListener

	public void focusGained(FocusEvent e) { // System.out.println( "focusGained: " );
	}

	public void focusLost(FocusEvent e) { // System.out.println( "focusLost: " );
		stopCellEditing();
	}

}