Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » JFace » Cell editor with StyledText (Tabbing between cells in the table viewer)
Cell editor with StyledText [message #545757] Fri, 09 July 2010 00:00 Go to next message
Seema  is currently offline Seema Friend
Messages: 14
Registered: December 2009
Junior Member
Hi,

I have a TableViewer with cell editors that are text editors but the text control is a Styled text.

I have an issue with tabbing between cells when only the last column is editable. When the first cell in the last column is in the edit mode, tabbing on the cell moves to the cell on the next row. This erases the text in the cell that has focus after tabbing. It probably inserts a tab character.

This behavior is not present when I use the TextEditor as the cell editor. I'm not sure why.
Can anyone please help ?

I have the snippet that I modified to create my snippet included along with the cell editor that I'm using.

package testSnippets;

import org.eclipse.jface.viewers.CellEditor;

/**
 * Shows how to setup a Viewer to start cell editing on double click
 *
 * @author Tom Schindl <tom.schindl@bestsolution.at>
 *
 */
public class Snippet052DouleClickCellEditor {

	private class MyContentProvider implements IStructuredContentProvider {

		/*
		 * (non-Javadoc)
		 *
		 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
		 */
		public Object[] getElements(Object inputElement) {
			return (MyModel[]) inputElement;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
		 */
		public void dispose() {

		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
		 *      java.lang.Object, java.lang.Object)
		 */
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

		}

	}

	public static boolean flag = true;

	public class MyModel {
		public int counter;

		public MyModel(int counter) {
			this.counter = counter;
		}

		public String toString() {
			return "Item " + this.counter;
		}
	}

	public Snippet052DouleClickCellEditor(Shell shell) {
		final TableViewer v = new TableViewer(shell, SWT.BORDER
				| SWT.FULL_SELECTION);
		v.setContentProvider(new MyContentProvider());
//		v.setCellEditors(new CellEditor[] { new TextCellEditor(v.getTable()),
//				new TextCellEditor(v.getTable()),
//				new TextCellEditor(v.getTable()) });
		v.setCellEditors(new CellEditor[] { new StyledTextCellEditor(v.getTable()),
				new StyledTextCellEditor(v.getTable()),
				new StyledTextCellEditor(v.getTable()) });
	
		v.setCellModifier(new ICellModifier() {

			public boolean canModify(Object element, String property) {
				if(property.equalsIgnoreCase("1") || property.equalsIgnoreCase("2") ){
					return false;
				}
				return true;
			}

			public Object getValue(Object element, String property) {
				return "Column " + property + " => " + element.toString();
			}

			public void modify(Object element, String property, Object value) {

			}

		});

		v.setColumnProperties(new String[] { "1", "2", "3" });

		ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
				v) {
			protected boolean isEditorActivationEvent(
					ColumnViewerEditorActivationEvent event) {
				return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
						|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
						|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
			}
		};

		TableViewerEditor.create(v, actSupport,
				ColumnViewerEditor.TABBING_HORIZONTAL
						| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
						| ColumnViewerEditor.TABBING_VERTICAL
						| ColumnViewerEditor.KEYBOARD_ACTIVATION);

		TableViewerColumn column = new TableViewerColumn(v, SWT.NONE);
		column.getColumn().setWidth(200);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Column 1");
		column.setLabelProvider(new ColumnLabelProvider());

		column = new TableViewerColumn(v, SWT.NONE);
		column.getColumn().setWidth(200);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Column 2");
		column.setLabelProvider(new ColumnLabelProvider());

		column = new TableViewerColumn(v, SWT.NONE);
		column.getColumn().setWidth(200);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Column 3");
		column.setLabelProvider(new ColumnLabelProvider());

		MyModel[] model = createModel();
		v.setInput(model);
		v.getTable().setLinesVisible(true);
		v.getTable().setHeaderVisible(true);
	}

	private MyModel[] createModel() {
		MyModel[] elements = new MyModel[10];

		for (int i = 0; i < 10; i++) {
			elements[i] = new MyModel(i);
		}

		return elements;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Display display = new Display();

		Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		new Snippet052DouleClickCellEditor(shell);
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}

		display.dispose();

	}

}



Here is the cell editor code:


package testSnippets;

import java.text.MessageFormat;

/**
 * A cell editor that manages a text entry field. The cell editor's value is the
 * text string itself.
 * <p>
 * This class may be instantiated; it is not intended to be sub-classed.
 * </p>
 * 
 * @noextend This class is not intended to be sub-classed by clients.
 */
public class StyledTextCellEditor extends CellEditor {

	/**
	 * The text control; initially <code>null</code>.
	 */
	protected StyledText text;
//	protected Text text;

	/**
	 * The value of this cell editor; initially <code>null</code>.
	 */
	private Object value = null;

	private ModifyListener modifyListener;

	/**
	 * State information for updating action enablement
	 */
	private boolean isSelection = false;

	private boolean isDeleteable = false;

	private boolean isSelectable = false;

	/**
	 * Default TextCellEditor style specify no borders on text widget as cell
	 * outline in table already provides the look of a border.
	 */
	private static final int defaultStyle = SWT.SINGLE;

	private Composite parent;

	private FocusListener textFocusListener;

	public StyledTextCellEditor(Composite parent){
		super(parent);		
	}

	/**
	 * Checks to see if the "delete-able" state (can delete/ nothing to delete)
	 * has changed and if so fire an enablement changed notification.
	 */
	private void checkDeleteable() {
		boolean oldIsDeleteable = isDeleteable;
		isDeleteable = isDeleteEnabled();
		if (oldIsDeleteable != isDeleteable) {
			fireEnablementChanged(DELETE);
		}
	}

	/**
	 * Checks to see if the "select-able" state (can select) has changed and if
	 * so fire an enablement changed notification.
	 */
	private void checkSelectable() {
		boolean oldIsSelectable = isSelectable;
		isSelectable = isSelectAllEnabled();
		if (oldIsSelectable != isSelectable) {
			fireEnablementChanged(SELECT_ALL);
		}
	}

	/**
	 * Checks to see if the selection state (selection / no selection) has
	 * changed and if so fire an enablement changed notification.
	 */
	private void checkSelection() {
		boolean oldIsSelection = isSelection;
		isSelection = text.getSelectionCount() > 0;
		if (oldIsSelection != isSelection) {
			fireEnablementChanged(COPY);
			fireEnablementChanged(CUT);
		}
	}

	/*
	 * (non-Javadoc) Method declared on CellEditor.
	 */
	protected Control createControl(Composite parent) {
		text = new StyledText(parent, SWT.SINGLE);
//		text = new Text(parent, SWT.SINGLE);
		text.setWordWrap(false);
		text.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(SelectionEvent e) {
				handleDefaultSelection(e);
			}
		});
		text.addKeyListener(new KeyAdapter() {
			// hook key pressed - see PR 14201
			public void keyPressed(KeyEvent e) {
				keyReleaseOccured(e);

				// as a result of processing the above call, clients may have
				// disposed this cell editor
				if ((getControl() == null) || getControl().isDisposed()) {
					return;
				}

				checkSelection(); // see explanation below
				checkDeleteable();
				checkSelectable();
			}
		});
		text.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if (e.detail == SWT.TRAVERSE_ESCAPE || e.detail == SWT.TRAVERSE_RETURN) {
					e.doit = false;
				}

				if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
					if (value != null ) {	
						value = text.getText();
					}
					keyReleaseOccured(e);
				}
			}
		});

		text.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				checkSelection();
				checkDeleteable();
				checkSelectable();
			}
		});
		text.addFocusListener(getTextFocusListener());

		text.setBackground(parent.getBackground());
		text.setText("");//$NON-NLS-1$
		text.addModifyListener(getModifyListener());

		return text;
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> framework method returns the text string.
	 * 
	 * @return the text string
	 */
	protected Object doGetValue() {
		return value;
	}

	/*
	 * (non-Javadoc) Method declared on CellEditor.
	 */
	protected void doSetFocus() {
		if (text != null) {
			text.selectAll();
			text.setFocus();
			checkSelection();
			checkDeleteable();
			checkSelectable();
		}
	}

	protected void setValueFromCellText() {
		String newValue = text.getText();
		doSetValue(newValue);
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> framework method accepts a text string (type
	 * <code>String</code>).
	 * 
	 * @param value
	 *            a text string (type <code>String</code>)
	 */
	protected void doSetValue(Object value) {
		this.value = value;
		if (text == null) {
			return;
		}

		String textValue = "";//$NON-NLS-1$
		if (value != null) {
			textValue = value.toString();
		}
		text.removeModifyListener(getModifyListener());		
		text.setText(textValue);
		text.addModifyListener(getModifyListener());
	}

	/**
	 * Processes a modify event that occurred in this text cell editor. This
	 * framework method performs validation and sets the error message
	 * accordingly, and then reports a change via
	 * <code>fireEditorValueChanged</code>. Subclasses should call this method
	 * at appropriate times. Subclasses may extend or re-implement.
	 * 
	 * @param e the SWT modify event
	 */
	protected void editOccured(ModifyEvent e) {
		String value = text.getText();
		if (value == null) {
			value = "";//$NON-NLS-1$
		}
		Object typedValue = value;
		boolean oldValidState = isValueValid();
		boolean newValidState = isCorrect(typedValue);
		if (typedValue == null && newValidState) {
			Assert.isTrue(false, "Validator isn't limiting the cell editor's type range");//$NON-NLS-1$
		}
		if (!newValidState) {
			// try to insert the current value into the error message.
			setErrorMessage(MessageFormat.format(getErrorMessage(), new Object[] { value }));
		}
		valueChanged(oldValidState, newValidState);
	}

	/**
	 * Since a text editor field is scrollable we don't set a minimumSize.
	 */
	public LayoutData getLayoutData() {
		return new LayoutData();

	}

	/**
	 * Return the modify listener.
	 */
	private ModifyListener getModifyListener() {
		if (modifyListener == null) {
			modifyListener = new ModifyListener() {
				public void modifyText(ModifyEvent e) {
					editOccured(e);
				}
			};
		}
		return modifyListener;
	}

	/**
	 * Handles a default selection event from the text control by applying the
	 * editor value and deactivating this cell editor.
	 * 
	 * @param event
	 *            the selection event
	 * 
	 * @since 3.0
	 */
	protected void handleDefaultSelection(SelectionEvent event) {
		// same with enter-key handling code in keyReleaseOccured(e);
		fireApplyEditorValue();
		deactivate();
	}

	protected void handleDefaultSelection() {
		// same with enter-key handling code in keyReleaseOccured(e);
		this.value = text.getText();
		fireApplyEditorValue();
		deactivate();
	}
	
	public void dispose() {
		if (text != null && !text.isDisposed()) {
			text.removeFocusListener(getTextFocusListener());
		}
		super.dispose();
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method returns <code>true</code> if the current
	 * selection is not empty.
	 */
	public boolean isCopyEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return text.getSelectionCount() > 0;
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method returns <code>true</code> if the current
	 * selection is not empty.
	 */
	public boolean isCutEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return text.getSelectionCount() > 0;
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method returns <code>true</code> if there is a
	 * selection or if the caret is not positioned at the end of the text.
	 */
	public boolean isDeleteEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return text.getSelectionCount() > 0 || text.getCaretOffset() < text.getCharCount();
//		return text.getSelectionCount() > 0 ;
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method always returns <code>true</code>.
	 */
	public boolean isPasteEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return true;
	}

	/**
	 * Check if save all is enabled
	 * 
	 * @return true if it is
	 */
	public boolean isSaveAllEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return true;
	}

	/**
	 * Returns <code>true</code> if this cell editor is able to perform the
	 * select all action.
	 * <p>
	 * This default implementation always returns <code>false</code>.
	 * </p>
	 * <p>
	 * Subclasses may override
	 * </p>
	 * 
	 * @return <code>true</code> if select all is possible, <code>false</code>
	 *         otherwise
	 */
	public boolean isSelectAllEnabled() {
		if (text == null || text.isDisposed()) {
			return false;
		}
		return text.getCharCount() > 0;
	}

	/**
	 * Processes a key release event that occurred in this cell editor.
	 * <p>
	 * The <code>TextCellEditor</code> implementation of this framework method
	 * ignores when the RETURN key is pressed since this is handled in
	 * <code>handleDefaultSelection</code>. An exception is made for Ctrl+Enter
	 * for multi-line texts, since a default selection event is not sent in this
	 * case.
	 * </p>
	 * 
	 * @param keyEvent
	 *            the key event
	 */
	protected void keyReleaseOccured(KeyEvent keyEvent) {
		if (keyEvent.character == '\r') { // Return key
			handleDefaultSelection();// pmisxp0
			// Enter is handled in handleDefaultSelection.
			// Do not apply the editor value in response to an Enter key event
			// since this can be received from the IME when the intent is -not-
			// to apply the value.
			// See bug 39074 [CellEditors] [DBCS] canna input mode fires bogus
			// event from Text Control
			//
			// An exception is made for Ctrl+Enter for multi-line texts, since
			// a default selection event is not sent in this case.
			if (text != null && !text.isDisposed() && (text.getStyle() & SWT.MULTI) != 0) {
				if ((keyEvent.stateMask & SWT.CTRL) != 0) {
					super.keyReleaseOccured(keyEvent);
				}
			}
			return;
		}
		super.keyReleaseOccured(keyEvent);
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method copies the current selection to the
	 * clipboard.
	 */
	public void performCopy() {
		text.copy();
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method cuts the current selection to the
	 * clipboard.
	 */
	public void performCut() {
		text.cut();
		checkSelection();
		checkDeleteable();
		checkSelectable();
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method deletes the current selection or, if there
	 * is no selection, the character next character from the current position.
	 */
	public void performDelete() {
		if (text.getSelectionCount() > 0) {
			// remove the contents of the current selection
			text.insert(""); //$NON-NLS-1$
		} else {
			// remove the next character
			int pos = text.getCaretOffset();
			if (pos < text.getCharCount()) {
				text.setSelection(pos, pos + 1);
				text.insert(""); //$NON-NLS-1$
			}
		}
		checkSelection();
		checkDeleteable();
		checkSelectable();
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method pastes the the clipboard contents over the
	 * current selection.
	 */
	public void performPaste() {
		text.paste();
		checkSelection();
		checkDeleteable();
		checkSelectable();
	}

	/**
	 * The <code>TextCellEditor</code> implementation of this
	 * <code>CellEditor</code> method selects all of the current text.
	 */
	public void performSelectAll() {
		text.selectAll();
		checkSelection();
		checkDeleteable();
	}

	/**
	 * This implementation of
	 * {@link CellEditor#dependsOnExternalFocusListener()} returns false if the
	 * current instance's class is TextCellEditorWithCaretDisplay, and true otherwise.
	 * Subclasses that hook their own focus listener should override this method
	 * and return false. See also bug 58777.
	 * 
	 * @since 3.4
	 */
	protected boolean dependsOnExternalFocusListener() {
		return getClass() != StyledTextCellEditor.class;		
	}

	@Override
	protected void deactivate(ColumnViewerEditorDeactivationEvent event) {

		super.deactivate(event);
	}

	public static int getDefaultstyle() {
		return defaultStyle;
	}

	public Composite getParent() {
		return parent;
	}

	protected FocusListener getTextFocusListener() {
		if (textFocusListener == null) {
			textFocusListener = new FocusAdapter() {
				@Override
				public void focusLost(FocusEvent event) {
					if (value != null || text.getText().length() != 0){
						doSetValue(text.getText());
						fireApplyEditorValue();
					} else if (value == null) {// if the field that is being
						// edited has a NULL value
						doSetValue(value);
						fireApplyEditorValue();
					}
				}			
			};
		}

		return textFocusListener;
	}
}



Thanks in advance.
Re: Cell editor with StyledText [message #545798 is a reply to message #545757] Fri, 09 July 2010 07:34 Go to previous messageGo to next message
Thomas Schindl is currently offline Thomas SchindlFriend
Messages: 6651
Registered: July 2009
Senior Member
Hi Seema,

I can confirm that this is happening but I have not the slightest idea
why. To me it looks like the TAB used to traverse is applied after the
editors have changed (probably the event orderning is different on
StyledText (Traverse, KeyDown/KeyUp) vs Text(KeyDown/KeyUp, Traverse?) ).

What's really strange is that I'm not even able to cancel the tab
processing by attaching a SWT.Down-Listener.

Tom

Am 09.07.10 02:00, schrieb Seema:
> Hi,
>
> I have a TableViewer with cell editors that are text editors but the
> text control is a Styled text.
>
> I have an issue with tabbing between cells when only the last column is
> editable. When the first cell in the last column is in the edit mode,
> tabbing on the cell moves to the cell on the next row. This erases the
> text in the cell that has focus after tabbing. It probably inserts a tab
> character.
>
> This behavior is not present when I use the TextEditor as the cell
> editor. I'm not sure why.
> Can anyone please help ?
>
> I have the snippet that I modified to create my snippet included along
> with the cell editor that I'm using.
>
>
> package testSnippets;
>
> import org.eclipse.jface.viewers.CellEditor;
>
> /**
> * Shows how to setup a Viewer to start cell editing on double click
> *
> * @author Tom Schindl <tom.schindl@bestsolution.at>
> *
> */
> public class Snippet052DouleClickCellEditor {
>
> private class MyContentProvider implements IStructuredContentProvider {
>
> /*
> * (non-Javadoc)
> *
> * @see
> org.eclipse.jface.viewers.IStructuredContentProvider#getElem ents(java.lang.Object)
>
> */
> public Object[] getElements(Object inputElement) {
> return (MyModel[]) inputElement;
> }
>
> /*
> * (non-Javadoc)
> *
> * @see org.eclipse.jface.viewers.IContentProvider#dispose()
> */
> public void dispose() {
>
> }
>
> /*
> * (non-Javadoc)
> *
> * @see
> org.eclipse.jface.viewers.IContentProvider#inputChanged(org. eclipse.jface.viewers.Viewer,
>
> * java.lang.Object, java.lang.Object)
> */
> public void inputChanged(Viewer viewer, Object oldInput, Object
> newInput) {
>
> }
>
> }
>
> public static boolean flag = true;
>
> public class MyModel {
> public int counter;
>
> public MyModel(int counter) {
> this.counter = counter;
> }
>
> public String toString() {
> return "Item " + this.counter;
> }
> }
>
> public Snippet052DouleClickCellEditor(Shell shell) {
> final TableViewer v = new TableViewer(shell, SWT.BORDER
> | SWT.FULL_SELECTION);
> v.setContentProvider(new MyContentProvider());
> // v.setCellEditors(new CellEditor[] { new
> TextCellEditor(v.getTable()),
> // new TextCellEditor(v.getTable()),
> // new TextCellEditor(v.getTable()) });
> v.setCellEditors(new CellEditor[] { new
> StyledTextCellEditor(v.getTable()),
> new StyledTextCellEditor(v.getTable()),
> new StyledTextCellEditor(v.getTable()) });
>
> v.setCellModifier(new ICellModifier() {
>
> public boolean canModify(Object element, String property) {
> if(property.equalsIgnoreCase("1") ||
> property.equalsIgnoreCase("2") ){
> return false;
> }
> return true;
> }
>
> public Object getValue(Object element, String property) {
> return "Column " + property + " => " + element.toString();
> }
>
> public void modify(Object element, String property, Object
> value) {
>
> }
>
> });
>
> v.setColumnProperties(new String[] { "1", "2", "3" });
>
> ColumnViewerEditorActivationStrategy actSupport = new
> ColumnViewerEditorActivationStrategy(
> v) {
> protected boolean isEditorActivationEvent(
> ColumnViewerEditorActivationEvent event) {
> return event.eventType ==
> ColumnViewerEditorActivationEvent.TRAVERSAL
> || event.eventType ==
> ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTI ON
> || event.eventType ==
> ColumnViewerEditorActivationEvent.PROGRAMMATIC;
> }
> };
>
> TableViewerEditor.create(v, actSupport,
> ColumnViewerEditor.TABBING_HORIZONTAL
> | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
> | ColumnViewerEditor.TABBING_VERTICAL
> | ColumnViewerEditor.KEYBOARD_ACTIVATION);
>
> TableViewerColumn column = new TableViewerColumn(v, SWT.NONE);
> column.getColumn().setWidth(200);
> column.getColumn().setMoveable(true);
> column.getColumn().setText("Column 1");
> column.setLabelProvider(new ColumnLabelProvider());
>
> column = new TableViewerColumn(v, SWT.NONE);
> column.getColumn().setWidth(200);
> column.getColumn().setMoveable(true);
> column.getColumn().setText("Column 2");
> column.setLabelProvider(new ColumnLabelProvider());
>
> column = new TableViewerColumn(v, SWT.NONE);
> column.getColumn().setWidth(200);
> column.getColumn().setMoveable(true);
> column.getColumn().setText("Column 3");
> column.setLabelProvider(new ColumnLabelProvider());
>
> MyModel[] model = createModel();
> v.setInput(model);
> v.getTable().setLinesVisible(true);
> v.getTable().setHeaderVisible(true);
> }
>
> private MyModel[] createModel() {
> MyModel[] elements = new MyModel[10];
>
> for (int i = 0; i < 10; i++) {
> elements[i] = new MyModel(i);
> }
>
> return elements;
> }
>
> /**
> * @param args
> */
> public static void main(String[] args) {
> Display display = new Display();
>
> Shell shell = new Shell(display);
> shell.setLayout(new FillLayout());
> new Snippet052DouleClickCellEditor(shell);
> shell.open();
>
> while (!shell.isDisposed()) {
> if (!display.readAndDispatch())
> display.sleep();
> }
>
> display.dispose();
>
> }
>
> }
>
>
>
> Here is the cell editor code:
>
>
>
> package testSnippets;
>
> import java.text.MessageFormat;
>
> /**
> * A cell editor that manages a text entry field. The cell editor's value
> is the
> * text string itself.
> * <p>
> * This class may be instantiated; it is not intended to be sub-classed.
> * </p>
> * * @noextend This class is not intended to be sub-classed by clients.
> */
> public class StyledTextCellEditor extends CellEditor {
>
> /**
> * The text control; initially <code>null</code>.
> */
> protected StyledText text;
> // protected Text text;
>
> /**
> * The value of this cell editor; initially <code>null</code>.
> */
> private Object value = null;
>
> private ModifyListener modifyListener;
>
> /**
> * State information for updating action enablement
> */
> private boolean isSelection = false;
>
> private boolean isDeleteable = false;
>
> private boolean isSelectable = false;
>
> /**
> * Default TextCellEditor style specify no borders on text widget as
> cell
> * outline in table already provides the look of a border.
> */
> private static final int defaultStyle = SWT.SINGLE;
>
> private Composite parent;
>
> private FocusListener textFocusListener;
>
> public StyledTextCellEditor(Composite parent){
> super(parent);
> }
>
> /**
> * Checks to see if the "delete-able" state (can delete/ nothing to
> delete)
> * has changed and if so fire an enablement changed notification.
> */
> private void checkDeleteable() {
> boolean oldIsDeleteable = isDeleteable;
> isDeleteable = isDeleteEnabled();
> if (oldIsDeleteable != isDeleteable) {
> fireEnablementChanged(DELETE);
> }
> }
>
> /**
> * Checks to see if the "select-able" state (can select) has changed
> and if
> * so fire an enablement changed notification.
> */
> private void checkSelectable() {
> boolean oldIsSelectable = isSelectable;
> isSelectable = isSelectAllEnabled();
> if (oldIsSelectable != isSelectable) {
> fireEnablementChanged(SELECT_ALL);
> }
> }
>
> /**
> * Checks to see if the selection state (selection / no selection) has
> * changed and if so fire an enablement changed notification.
> */
> private void checkSelection() {
> boolean oldIsSelection = isSelection;
> isSelection = text.getSelectionCount() > 0;
> if (oldIsSelection != isSelection) {
> fireEnablementChanged(COPY);
> fireEnablementChanged(CUT);
> }
> }
>
> /*
> * (non-Javadoc) Method declared on CellEditor.
> */
> protected Control createControl(Composite parent) {
> text = new StyledText(parent, SWT.SINGLE);
> // text = new Text(parent, SWT.SINGLE);
> text.setWordWrap(false);
> text.addSelectionListener(new SelectionAdapter() {
> public void widgetDefaultSelected(SelectionEvent e) {
> handleDefaultSelection(e);
> }
> });
> text.addKeyListener(new KeyAdapter() {
> // hook key pressed - see PR 14201
> public void keyPressed(KeyEvent e) {
> keyReleaseOccured(e);
>
> // as a result of processing the above call, clients may
> have
> // disposed this cell editor
> if ((getControl() == null) || getControl().isDisposed()) {
> return;
> }
>
> checkSelection(); // see explanation below
> checkDeleteable();
> checkSelectable();
> }
> });
> text.addTraverseListener(new TraverseListener() {
> public void keyTraversed(TraverseEvent e) {
> if (e.detail == SWT.TRAVERSE_ESCAPE || e.detail ==
> SWT.TRAVERSE_RETURN) {
> e.doit = false;
> }
>
> if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail ==
> SWT.TRAVERSE_TAB_PREVIOUS) {
> if (value != null ) {
> value = text.getText();
> }
> keyReleaseOccured(e);
> }
> }
> });
>
> text.addMouseListener(new MouseAdapter() {
> public void mouseUp(MouseEvent e) {
> checkSelection();
> checkDeleteable();
> checkSelectable();
> }
> });
> text.addFocusListener(getTextFocusListener());
>
> text.setBackground(parent.getBackground());
> text.setText("");//$NON-NLS-1$
> text.addModifyListener(getModifyListener());
>
> return text;
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> framework method returns the text string.
> * * @return the text string
> */
> protected Object doGetValue() {
> return value;
> }
>
> /*
> * (non-Javadoc) Method declared on CellEditor.
> */
> protected void doSetFocus() {
> if (text != null) {
> text.selectAll();
> text.setFocus();
> checkSelection();
> checkDeleteable();
> checkSelectable();
> }
> }
>
> protected void setValueFromCellText() {
> String newValue = text.getText();
> doSetValue(newValue);
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> framework method accepts a text string (type
> * <code>String</code>).
> * * @param value
> * a text string (type <code>String</code>)
> */
> protected void doSetValue(Object value) {
> this.value = value;
> if (text == null) {
> return;
> }
>
> String textValue = "";//$NON-NLS-1$
> if (value != null) {
> textValue = value.toString();
> }
> text.removeModifyListener(getModifyListener());
> text.setText(textValue);
> text.addModifyListener(getModifyListener());
> }
>
> /**
> * Processes a modify event that occurred in this text cell editor.
> This
> * framework method performs validation and sets the error message
> * accordingly, and then reports a change via
> * <code>fireEditorValueChanged</code>. Subclasses should call this
> method
> * at appropriate times. Subclasses may extend or re-implement.
> * * @param e the SWT modify event
> */
> protected void editOccured(ModifyEvent e) {
> String value = text.getText();
> if (value == null) {
> value = "";//$NON-NLS-1$
> }
> Object typedValue = value;
> boolean oldValidState = isValueValid();
> boolean newValidState = isCorrect(typedValue);
> if (typedValue == null && newValidState) {
> Assert.isTrue(false, "Validator isn't limiting the cell
> editor's type range");//$NON-NLS-1$
> }
> if (!newValidState) {
> // try to insert the current value into the error message.
> setErrorMessage(MessageFormat.format(getErrorMessage(), new
> Object[] { value }));
> }
> valueChanged(oldValidState, newValidState);
> }
>
> /**
> * Since a text editor field is scrollable we don't set a minimumSize.
> */
> public LayoutData getLayoutData() {
> return new LayoutData();
>
> }
>
> /**
> * Return the modify listener.
> */
> private ModifyListener getModifyListener() {
> if (modifyListener == null) {
> modifyListener = new ModifyListener() {
> public void modifyText(ModifyEvent e) {
> editOccured(e);
> }
> };
> }
> return modifyListener;
> }
>
> /**
> * Handles a default selection event from the text control by
> applying the
> * editor value and deactivating this cell editor.
> * * @param event
> * the selection event
> * * @since 3.0
> */
> protected void handleDefaultSelection(SelectionEvent event) {
> // same with enter-key handling code in keyReleaseOccured(e);
> fireApplyEditorValue();
> deactivate();
> }
>
> protected void handleDefaultSelection() {
> // same with enter-key handling code in keyReleaseOccured(e);
> this.value = text.getText();
> fireApplyEditorValue();
> deactivate();
> }
>
> public void dispose() {
> if (text != null && !text.isDisposed()) {
> text.removeFocusListener(getTextFocusListener());
> }
> super.dispose();
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method returns <code>true</code> if the
> current
> * selection is not empty.
> */
> public boolean isCopyEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return text.getSelectionCount() > 0;
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method returns <code>true</code> if the
> current
> * selection is not empty.
> */
> public boolean isCutEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return text.getSelectionCount() > 0;
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method returns <code>true</code> if there
> is a
> * selection or if the caret is not positioned at the end of the text.
> */
> public boolean isDeleteEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return text.getSelectionCount() > 0 || text.getCaretOffset() <
> text.getCharCount();
> // return text.getSelectionCount() > 0 ;
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method always returns <code>true</code>.
> */
> public boolean isPasteEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return true;
> }
>
> /**
> * Check if save all is enabled
> * * @return true if it is
> */
> public boolean isSaveAllEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return true;
> }
>
> /**
> * Returns <code>true</code> if this cell editor is able to perform the
> * select all action.
> * <p>
> * This default implementation always returns <code>false</code>.
> * </p>
> * <p>
> * Subclasses may override
> * </p>
> * * @return <code>true</code> if select all is possible,
> <code>false</code>
> * otherwise
> */
> public boolean isSelectAllEnabled() {
> if (text == null || text.isDisposed()) {
> return false;
> }
> return text.getCharCount() > 0;
> }
>
> /**
> * Processes a key release event that occurred in this cell editor.
> * <p>
> * The <code>TextCellEditor</code> implementation of this framework
> method
> * ignores when the RETURN key is pressed since this is handled in
> * <code>handleDefaultSelection</code>. An exception is made for
> Ctrl+Enter
> * for multi-line texts, since a default selection event is not sent
> in this
> * case.
> * </p>
> * * @param keyEvent
> * the key event
> */
> protected void keyReleaseOccured(KeyEvent keyEvent) {
> if (keyEvent.character == '\r') { // Return key
> handleDefaultSelection();// pmisxp0
> // Enter is handled in handleDefaultSelection.
> // Do not apply the editor value in response to an Enter key
> event
> // since this can be received from the IME when the intent
> is -not-
> // to apply the value.
> // See bug 39074 [CellEditors] [DBCS] canna input mode fires
> bogus
> // event from Text Control
> //
> // An exception is made for Ctrl+Enter for multi-line texts,
> since
> // a default selection event is not sent in this case.
> if (text != null && !text.isDisposed() && (text.getStyle() &
> SWT.MULTI) != 0) {
> if ((keyEvent.stateMask & SWT.CTRL) != 0) {
> super.keyReleaseOccured(keyEvent);
> }
> }
> return;
> }
> super.keyReleaseOccured(keyEvent);
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method copies the current selection to the
> * clipboard.
> */
> public void performCopy() {
> text.copy();
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method cuts the current selection to the
> * clipboard.
> */
> public void performCut() {
> text.cut();
> checkSelection();
> checkDeleteable();
> checkSelectable();
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method deletes the current selection or,
> if there
> * is no selection, the character next character from the current
> position.
> */
> public void performDelete() {
> if (text.getSelectionCount() > 0) {
> // remove the contents of the current selection
> text.insert(""); //$NON-NLS-1$
> } else {
> // remove the next character
> int pos = text.getCaretOffset();
> if (pos < text.getCharCount()) {
> text.setSelection(pos, pos + 1);
> text.insert(""); //$NON-NLS-1$
> }
> }
> checkSelection();
> checkDeleteable();
> checkSelectable();
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method pastes the the clipboard contents
> over the
> * current selection.
> */
> public void performPaste() {
> text.paste();
> checkSelection();
> checkDeleteable();
> checkSelectable();
> }
>
> /**
> * The <code>TextCellEditor</code> implementation of this
> * <code>CellEditor</code> method selects all of the current text.
> */
> public void performSelectAll() {
> text.selectAll();
> checkSelection();
> checkDeleteable();
> }
>
> /**
> * This implementation of
> * {@link CellEditor#dependsOnExternalFocusListener()} returns false
> if the
> * current instance's class is TextCellEditorWithCaretDisplay, and
> true otherwise.
> * Subclasses that hook their own focus listener should override
> this method
> * and return false. See also bug 58777.
> * * @since 3.4
> */
> protected boolean dependsOnExternalFocusListener() {
> return getClass() != StyledTextCellEditor.class;
> }
>
> @Override
> protected void deactivate(ColumnViewerEditorDeactivationEvent event) {
>
> super.deactivate(event);
> }
>
> public static int getDefaultstyle() {
> return defaultStyle;
> }
>
> public Composite getParent() {
> return parent;
> }
>
> protected FocusListener getTextFocusListener() {
> if (textFocusListener == null) {
> textFocusListener = new FocusAdapter() {
> @Override
> public void focusLost(FocusEvent event) {
> if (value != null || text.getText().length() != 0){
> doSetValue(text.getText());
> fireApplyEditorValue();
> } else if (value == null) {// if the field that is
> being
> // edited has a NULL value
> doSetValue(value);
> fireApplyEditorValue();
> }
> }
> };
> }
>
> return textFocusListener;
> }
> }
>
>
>
> Thanks in advance.
Re: Cell editor with StyledText [message #545887 is a reply to message #545798] Fri, 09 July 2010 14:35 Go to previous message
Seema  is currently offline Seema Friend
Messages: 14
Registered: December 2009
Junior Member
Never mind. I got it. If someone has the same problem I wanted to let you know that I had to add a verify listener to fix my problem.

I added :
text.addVerifyKeyListener(new VerifyKeyListener() {
            public void verifyKey(VerifyEvent e){
            	if(e.keyCode == SWT.TAB){
            		e.doit = false;
            	}
            }            
        });
Previous Topic:Drop problem with ListViewer
Next Topic:Problem with JFace GraphViewer in RCP view and commands
Goto Forum:
  


Current Time: Sat Apr 20 02:01:13 GMT 2024

Powered by FUDForum. Page generated in 0.02586 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top