Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

JFace/SWT content assist cell editor implementation

// a cell editor implementation providing autocompletion capabilities for JTable editing

import java.text.MessageFormat;

import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.fieldassist.TextControlCreator;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.fieldassist.ContentAssistField;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;

/**
 * A cell editor that manages a content assist field.
 * The cell editor's value is the text string itself.
 * 
 * This class may be instantiated; it is not intended to be subclassed.
 * 
 */
public class ContentAssistFieldCellEditor extends CellEditor 
{
	protected ContentAssistField field;
	
	protected IContentProposalProvider contentProposalProvider; 
    
	protected char[] completionProposalAutoActivationCharacters;
	
    private ModifyListener modifyListener;
    
    public ContentAssistFieldCellEditor( char[] completionProposalAutoActivationCharacters, IContentProposalProvider contentProposalProvider) 
    {
		super();
		this.completionProposalAutoActivationCharacters = completionProposalAutoActivationCharacters;
		this.contentProposalProvider = contentProposalProvider;
	}

    /**
     * Return the modify listener.
     */
    private ModifyListener getModifyListener() {
        if (modifyListener == null) {
            modifyListener = new ModifyListener() {
                public void modifyText(ModifyEvent e) {
                    editOccured(e);
                }
            };
        }
        return modifyListener;
    }
    
	public ContentAssistFieldCellEditor(Composite parent, int style, char[] completionProposalAutoActivationCharacters, IContentProposalProvider contentProposalProvider) {
		super( parent, style);
	}

	public ContentAssistFieldCellEditor(Composite parent,char[] completionProposalAutoActivationCharacters, IContentProposalProvider contentProposalProvider) 
	{
		super(parent);
	}

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

    private boolean isDeleteable = false;

    private boolean isSelectable = false;
    
    private Text text;
    
    @Override
   	protected Control createControl(Composite parent) 
    {
    	//SimpleContentProposalProvider proposelProvider = new SimpleContentProposalProvider( new String[] { "a", "b", "c"});  
    	
    	field = new ContentAssistField( 	
			parent, 
			SWT.SINGLE,
			new TextControlCreator(),
			new TextContentAdapter(),
			contentProposalProvider,
			ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS,
			completionProposalAutoActivationCharacters
		);
    	
    	text = (Text)field.getControl();
    	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 explaination 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;
                }
            }
        });
        // We really want a selection listener but it is not supported so we
        // use a key listener and a mouse listener to know when selection changes
        // may have occured
        text.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                checkSelection();
                checkDeleteable();
                checkSelectable();
            }
        });
        text.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent e) {
                ContentAssistFieldCellEditor.this.focusLost();
            }
        });
        text.setFont(parent.getFont());
        text.setBackground(parent.getBackground());
        text.setText("");//$NON-NLS-1$
        text.addModifyListener( getModifyListener());
    	
    	return field.getLayoutControl();
    }
    
    /**
     * Checks to see if the "deleteable" 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 "selectable" 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);
        }
    }
    
    /**
     * 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 fireEditorValueChanged.
     * Subclasses should call this method at appropriate times. Subclasses
     * may extend or reimplement.
     *
     * @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);
    }
    
    /**
     * Handles a default selection event from the text control by applying the editor
     * value and deactivating this cell editor.
     * 
     * @param event the selection event
     */
    protected void handleDefaultSelection(SelectionEvent event) 
    {
        // same with enter-key handling code in keyReleaseOccured(e);
        fireApplyEditorValue();
        deactivate();
    }
    
    @Override
    protected void doSetFocus() 
    {
    	if( field!= null) {
            field.getControl().setFocus();
        }
    }
    
    @Override
    protected Object doGetValue() 
    {
    	return ((Text)field.getControl()).getText();
    }
    
    @Override
    protected void doSetValue(Object value) 
    {
    	((Text)field.getControl()).setText( value.toString());
    }
    
    /**
     * The implementation of this
     *  method copies the
     * current selection to the clipboard. 
     */
    public void performCopy() {
        text.copy();
    }

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

    /**
     * The implementation of this
     *  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.getCaretPosition();
            if (pos < text.getCharCount()) {
                text.setSelection(pos, pos + 1);
                text.insert(""); //$NON-NLS-1$
            }
        }
        checkSelection();
        checkDeleteable();
        checkSelectable();
    }

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

    /**
     * The implementation of this
     *  method selects all of the
     * current text. 
     */
    public void performSelectAll() {
        text.selectAll();
        checkSelection();
        checkDeleteable();
    }
    
    
    
    /**
     * Since a text editor field is scrollable we don't
     * set a minimumSize.
     */
    public LayoutData getLayoutData() {
        return new LayoutData();
    }
    
    /**
     * Processes a key release event that occurred in this cell editor.
     * 
     * The implementation of this framework method 
     * ignores when the RETURN key is pressed since this is handled in 
     * handleDefaultSelection.
     * An exception is made for Ctrl+Enter for multi-line texts, since
     * a default selection event is not sent in this case. 
     * 
     *
     * @param keyEvent the key event
     */
    protected void keyReleaseOccured(KeyEvent keyEvent) {
        if (keyEvent.character == '\r') { // Return key
            // 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);
    }
}

content assist field descriptor implementation reusing my ContentAssistFieldCellEditor.

Using this class lets you easily configure a Eclipse IPropertySource with autocompletion fields.
See my ContentAssistFieldCellEditor implementation.

import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.views.properties.PropertyDescriptor;

public class ContentAssistFieldDescriptor extends PropertyDescriptor 
{	
	protected char[] completionProposalAutoActivationCharacters;
	protected IContentProposalProvider contentProposalProvider;
	    /**
	     * Creates an property descriptor with the given id and display name.
	     * 
	     * @param id the id of the property
	     * @param displayName the name to display for the property
	     */
	public ContentAssistFieldDescriptor(Object id, String displayName, char[] completionProposalAutoActivationCharacters, IContentProposalProvider contentProposalProvider) 
	{
        super( id, displayName);
        
        this.completionProposalAutoActivationCharacters = completionProposalAutoActivationCharacters;
        this.contentProposalProvider = contentProposalProvider;
    }
	
	    /**
	     * The ContentAssistFieldPropertyDescriptor implementation of this 
	     * IPropertyDescriptor method creates and returns a new
	     * TextCellEditor.
	     * 
	     * The editor is configured with the current validator if there is one.
	     * 
	     */
    @Override
    public CellEditor createPropertyEditor(Composite parent) 
    {
    	ContentAssistFieldCellEditor editor = new ContentAssistFieldCellEditor( parent, completionProposalAutoActivationCharacters, contentProposalProvider);
        if (getValidator() != null) 
        {
	     editor.setValidator(getValidator());
	}
        return editor;
    }
}

CSpinner for SWT

This is a simple Spinner component for SWT
It's not complete and it's -for sure- not very eye-pleasing.

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Text;

public class CSpinner extends Composite {
    private Text text;
    private Slider slider;
    private int value = 119;
    
    public CSpinner(Composite parent, int style) {
        super(parent, SWT.BORDER | style);

        GridLayout thisLayout = new GridLayout();
        thisLayout.horizontalSpacing = 0;
        thisLayout.numColumns = 2;
        thisLayout.marginHeight = 0;
        thisLayout.marginWidth = 0;
        thisLayout.verticalSpacing = 0;
        setLayout(thisLayout);
        setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        
        text = new Text(this, SWT.NONE);
        text.setText("" + value);
        text.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                try {
                    value = Integer.parseInt(text.getText());
                    slider.setSelection(value);
                    text.setBackground(new Color(getDisplay(), 255, 255, 255));
                    text.setToolTipText("");
                } catch(NumberFormatException e1) {
                    text.setBackground(new Color(getDisplay(), 255, 192, 192));
                    text.setToolTipText("Only integer values are accepted.");
                }
            }
        });
        text.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL));
        slider = new Slider(this, SWT.VERTICAL);
        slider.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                text.setText("" + slider.getSelection());
            }
        });
        slider.setValues(value, 0, 65535, 1, 1, 10);
        GridData sliderLData = new GridData();
        sliderLData.widthHint = 14;
        sliderLData.heightHint = 21;
        slider.setLayoutData(sliderLData);
    }
    
    public String getText() {
        return text.getText();
    }
}

TableEditor in SWT

This code shows some table cell editors for SWT
it's not complete, but you can get a hint

import java.util.HashMap;
import java.util.Random;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class TableTester {
	
	private Display display;
	private Shell shell;
	private HashMap<String, Image> hashImages;
	private Table table;
	
	private Color GRAY;
	private Color WHITE;
	private int EDITABLECOLUMN;
	
	public TableTester() {
		display = new Display();
		shell = new Shell(display);
		
		init();
		createGUI();
		
		shell.open();
		
		while(!shell.isDisposed()) {
			if(!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	private void init() {
		hashImages = new HashMap<String, Image>();
		hashImages.put("help", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\help.png"));
		hashImages.put("about", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\about_kde.png"));
		
		GRAY = new Color(display, 220, 220, 220);
		WHITE = new Color(display, 255, 255, 255);
	}
	
	private void createGUI() {
		shell.setLayout(new FillLayout());
		shell.setText("TableTester");
		
		shell.setImage(hashImages.get("about"));
		
		table = new Table(shell, SWT.SINGLE | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.VIRTUAL);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		table.addListener (SWT.MouseDown, new Listener () {
			public void handleEvent (Event event) {
				Rectangle clientArea = table.getClientArea ();
				Point selectedPoint = new Point (event.x, event.y);
				int index = table.getTopIndex ();
				while (index < table.getItemCount ()) {
					boolean visible = false;
					TableItem item = table.getItem (index);
					for (int i=0; i < table.getColumnCount(); i++) {
						Rectangle rect = item.getBounds (i);
						if (rect.contains (selectedPoint)) {
//							System.out.println ("Item " + index + "-" + i);
							EDITABLECOLUMN = i;
						}
						if (!visible && rect.intersects (clientArea)) {
							visible = true;
						}
					}
					if (!visible) return;
					index++;
				}
			}
		});
		
		final TableEditor editor = new TableEditor(table);
		//The editor must have the same size as the cell and must
		//not be any smaller than 50 pixels.
		editor.horizontalAlignment = SWT.LEFT;
		editor.grabHorizontal = true;
		editor.minimumWidth = 50;
		
		table.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				// Clean up any previous editor control
				Control oldEditor = editor.getEditor();
				if (oldEditor != null) oldEditor.dispose();
		
				// Identify the selected row
				TableItem item = (TableItem)e.item;
				if (item == null) {
					return;
				}

				// The control that will be the editor must be a child of the Table
				if(EDITABLECOLUMN == 0) { // boolean
					if("true".equalsIgnoreCase(item.getText())) {
						final Button newEditor = new Button(table, SWT.CHECK);
						newEditor.setText("Click to change");
						newEditor.setSelection(true);
						newEditor.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								editor.getItem().setText("" + newEditor.getSelection());
							}
						});
						newEditor.setFocus();
						editor.setEditor(newEditor, item, EDITABLECOLUMN);
					} else {
						final Button newEditor = new Button(table, SWT.CHECK);
						newEditor.setText("Click to change");
						newEditor.setSelection(false);
						newEditor.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								editor.getItem().setText("" + newEditor.getSelection());
							}
						});
						newEditor.setFocus();
						editor.setEditor(newEditor, item, EDITABLECOLUMN);
					}
				} else if(EDITABLECOLUMN == 3) { // password string
					Button newEditor = new Button(table, SWT.NONE);
					newEditor.setText("Generate");
					newEditor.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent e) {
							String s = Utilities.getRandomString(12, true, true, true, true);
							editor.getItem().setText(EDITABLECOLUMN, s);
						}
					});
					newEditor.setFocus();
					editor.setEditor(newEditor, item, EDITABLECOLUMN);
				} else if(EDITABLECOLUMN == 4) { // color
					ColorDialog newEditor = new ColorDialog(shell, SWT.NONE);
					String[] data = item.getText(EDITABLECOLUMN).split(",");
					newEditor.setRGB(new RGB(Integer.parseInt(data[0].trim()),
							Integer.parseInt(data[1].trim()),
							Integer.parseInt(data[2].trim())));
					RGB rgb = newEditor.open();
					item.setText(EDITABLECOLUMN, rgb.red + "," + rgb.green + "," + rgb.blue);
				} else {
					Text newEditor = new Text(table, SWT.NONE);
					newEditor.setText(item.getText(EDITABLECOLUMN));
					newEditor.addModifyListener(new ModifyListener() {
						public void modifyText(ModifyEvent me) {
							Text text = (Text)editor.getEditor();
							editor.getItem().setText(EDITABLECOLUMN, text.getText());
						}
					});
					newEditor.selectAll();
					newEditor.setFocus();
					editor.setEditor(newEditor, item, EDITABLECOLUMN);
				}
			}
		});
		
		fillWithData();
	}
	
	private void fillWithData() {
		TableColumn col = new TableColumn(table, SWT.NONE);
		col.setText("boolean");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Integer");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Float");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Password");
		col.setWidth(100);

		col = new TableColumn(table, SWT.NONE);
		col.setText("Color");
		col.setWidth(100);
		
		TableItem row;
		Random r = new Random(System.nanoTime());
		for (int i = 0; i < 1000; i++) {
			row = new TableItem(table, SWT.NONE);
			row.setText(new String[] {
					"" + r.nextBoolean(),
					"" + r.nextInt(),
					"" + r.nextFloat(),
					"" + Utilities.getRandomString(12, true, true, true, true),
					"" + r.nextInt(255) + "," + r.nextInt(255) + "," + r.nextInt(255)});
			row.setBackground((i % 2 == 0) ? WHITE : GRAY);
		}
	}

	public static void main(String[] args) {
		new TableTester();
	}
}

Simple Wizard in SWT

// This code is an example for StackLayout

import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widget