View Javadoc

1   package unbbayes.gui.table;
2   
3   import java.awt.Component;
4   import java.awt.event.FocusAdapter;
5   import java.awt.event.FocusEvent;
6   
7   import javax.swing.DefaultCellEditor;
8   import javax.swing.JTable;
9   import javax.swing.JTextField;
10  
11  /**
12   * Class responsible for replacing the old value by the new value typed instead of appending it.
13   * However, if the focus is gained by something different than by typing a new value, then it 
14   * just selects all the text inside the text field component.
15   */
16  public class ReplaceTextCellEditor extends DefaultCellEditor {
17  	private static final long serialVersionUID = 1L;
18  
19  	protected JTextField textField = new JTextField();
20  	protected String previousValue = "";
21  
22  	public ReplaceTextCellEditor() {
23  		super(new JTextField());
24  		this.textField = (JTextField) this.editorComponent;
25  		
26  		this.textField.addFocusListener(new FocusAdapter() {
27  			public void focusGained(FocusEvent e) {
28  				// New value that the text field has.
29  				String text = textField.getText();
30  				// If it is the same, just select it all.
31  				if (previousValue.equals(text)) {
32  					textField.selectAll();
33  				// If it is different than what it had before, than just replace the 
34  				// previous value by the new value typed (text - previousValue). 
35  				// Because text = previousValue + newValueTyped.
36  				} else if (text.length() > 0 && previousValue.length() < text.length()) {
37  					textField.setText(text.substring(previousValue.length()));
38  				}
39  			}
40  		});
41  		
42  	}
43  
44  	public void setValue(Object value) {
45  		textField.setText((value != null) ? value.toString() : "");
46  	}
47  
48  	public Object getCellEditorValue() {
49  		return textField.getText();
50  	}
51  
52  	public Component getTableCellEditorComponent(JTable table, Object value,
53  			boolean isSelected, int row, int column) {
54  		
55  		if (isSelected == false) {
56  			return null;
57  		}
58  
59  		// Used to control what to do when the text filed gains focus (select all or replace text).
60  		this.previousValue = value.toString();
61  
62  		this.textField.setText(this.previousValue);
63  		
64  		
65  
66  		return this.textField;
67  	}
68  
69  }