BUG Community

Welcome! Log In

bballantine's Blog

JFace EditingSupport for Custom Tables

Stan Lee in Spider Man taught us that, "With great power there must also come -- great responsibility!"  I think about that quote when working on Eclipse plug-ins, only it changes in my head to read, "With great power there must also come -- great complexity!"  Eclipse provides the building blocks to do wonderfully powerful things, but to wade into plug-in development is to wade into all sorts of complexity. 

My most recent responsibility/complexity was to make a service properties chooser/editor in the BUG Application code generation wizard.  This functionality (still in development at the time of this writing), will allow BUG Application developers tighter control of the filters used by the Application's Service Tracker.

Service property values are stored as strings, but they can represent booleans, numbers, or Strings.  I wanted to create a table where each row is a service property key/value pair.  The developer can then choose the properties they want to include in the filter and modify the values for that property.  Moreover, I wanted the property value to be editable like a text field for things like numbers, but use a combo box for things like boolean values.  Here's what the table looks like:

created on: 07/21/09

It looks straight forward enough, but the implementation turned out to be rather challenging.  The custom behavior of the cells pushed me toward using JFace CellEditorS and EditingSupport.  I found some tutorials and code-snippets on-line, but nothing suited my specific needs, which were to have checkbox support and selection events on the rows, plus different CellEditorS for each of the second column's cells, depending on the type of value.  The most helpful tutorial I found is here: http://www.vogella.de/articles/EclipseJFaceTable/article.html.  It didn't solve all my problems, but it certainly gave me a start.

After some time-consuming web-slinging, pining over the above tutorial, and some old-fashion trial and error, I was able to finally make the thing work.  Here, I share my solution in the hope that it will help where other resources fall short:

First, let's start out with the class.  This particular JFace component was added to a WizardPage:

public class CodeGenerationPage extends WizardPage {

Next, define our main TableViewer as an instance variable:

// Main JFace component private CheckboxTableViewer servicePropertiesViewer;

All of the wizard page drawing is kicked off from the createControl method, which you must override.  Inside there, we create the JFace components -- a CheckboxTableViewer which is the surrounding table, and TableColumnViewerS for the columns -- and put it all together:

// table with list of properties to choose from // compServices is a Group that we're putting all of this stuff in final Table propertiesTable = new Table( compServices, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION); propertiesTable.setHeaderVisible(true); propertiesTable.setLinesVisible(true); // layout of columns in table TableLayout propTableLayout = new TableLayout(); propTableLayout.addColumnData(new ColumnWeightData(90)); propTableLayout.addColumnData(new ColumnWeightData(120)); propertiesTable.setLayout(propTableLayout); // layout of table on the page GridData pViewerData = new GridData(GridData.FILL_BOTH); pViewerData.horizontalSpan = layout.numColumns; pViewerData.heightHint = SERVICE_PROPERTIES_HEIGHT_HINT; propertiesTable.setLayoutData(pViewerData); // viewer for services list servicePropertiesViewer = new CheckboxTableViewer(propertiesTable); servicePropertiesViewer.setContentProvider(new ServicePropsContentProvider()); // Add a listener to do something when a checkbox on a row is selected servicePropertiesViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { // You can do something when a row is selected here } }); // Column 0 - checkbox and property name // col0 is taken care of by checkboxtableviewer TableViewerColumn col0viewer = new TableViewerColumn(servicePropertiesViewer, SWT.FULL_SELECTION, 0); // TableViewerColumn needs a label provider col0viewer.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((ServicePropertyHelper) element).getKey(); } }); col0viewer.getColumn().setText(KEY_LABEL); // Column 1 - property value w/ celleditors // col1 has custom cell editors defined in EditingSupport below TableViewerColumn col1viewer = new TableViewerColumn(servicePropertiesViewer, SWT.FULL_SELECTION, 1); col1viewer.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((ServicePropertyHelper) element).getSelectedValue(); } }); col1viewer.getColumn().setText(VALUE_LABEL); // col1viewer has editing support - // this is where the magic happens that sets a different celleditor depending col1viewer.setEditingSupport( new PropertyValueEditingSupport(col1viewer.getViewer()));

The comments in the code should help explain things, but there are two items worthy of extra attention.  First, by using a CheckboxTableViewer, we can get a selection event from the table and also access selected elements via servicePropertiesViewer.getCheckedElements().  For the second column's CellEditorS, we need to decide, per-cell, which editor to use (whether to use a TextCellEditor or a ComboBoxCellEditor) based on what the potential values are.  We do this by adding EditingSupport to the column, i.e. col1viewer.setEditingSupport().  Here is most of the EditingSupport implementation (with all the helper functions stripped out for brevity):

public class PropertyValueEditingSupport extends EditingSupport { private final String[] truefalse = new String[] {"true", "false"}; private Composite parent; private TextCellEditor text_editor; private ComboBoxCellEditor combobox_editor; public PropertyValueEditingSupport(ColumnViewer viewer) { super(viewer); parent =((TableViewer) viewer).getTable(); text_editor = new TextCellEditor(parent); combobox_editor = new ComboBoxCellEditor(parent, new String[0]); } @Override protected boolean canEdit(Object element) { return true; } @Override protected CellEditor getCellEditor(Object element) { ServicePropertyHelper propertyHelper = ((ServicePropertyHelper) element); if (usesTextEditor(propertyHelper.getValues())) { // Ints and blanks use text editor return text_editor; } else { // everything else uses a combobox if (hasBools(propertyHelper.getValues())) // boolean combos prefill w/ true and false combobox_editor.setItems(truefalse); else // other types, just do set the combobox to values combobox_editor.setItems(propertyHelper.getValuesAsArray()); return combobox_editor; } } @Override protected Object getValue(Object element) { ServicePropertyHelper propertyHelper = ((ServicePropertyHelper) element); if (usesTextEditor(propertyHelper.getValues())) { return propertyHelper.getSelectedValue(); } else { return Integer.valueOf(propertyHelper.getSelectedIndex()); } } @Override protected void setValue(Object element, Object value) { // Get the current service that's been selected ServicePropertyHelper propertyHelper = ((ServicePropertyHelper) element); if (usesTextEditor(propertyHelper.getValues())) { // if it's a text field, just set the value propertyHelper.setSelectedValue("" + value); } else if (hasBools(propertyHelper.getValues())) { // if it's a boolean, value is an index in truefalse array propertyHelper.setSelectedValue(truefalse[Integer.valueOf("" + value)]); } else { // if it's something else, value is an index in the service property values set String val = propertyHelper.getValueAt(Integer.valueOf("" + value)); if (val != null) propertyHelper.setSelectedValue(val); } getViewer().update(element, null); } }

In the constructor, we create our two CellEditorS.  We then override getCellEditor(Object element) to return the proper cell editor for the passed element.  Element is an element in the array returned from servicePropertiesViewer's ContentProvider.getElements() method (I must point out that the relationship between a TableViewer, it's ContentProvider, it's TableViewerColumnS, and a TableViewerColumn's EditingSupport is pretty confusing.  The tutorial mentioned above should help clear all that up if you're lost.  Also, if you're still in the dark about JFace viewers, label providers, content providers, and inputs, Eclipse: Building Commercial-Quality Plug-ins is a must-read).  We must also override a couple of other EditingSupport methods: canEdit(), getValue(Object element), and setValue(Object element, Object value).  The important thing to note is that the values (given and returned) for a TextCellEditor are Strings, and for a ComboBoxCellEditor, Integers.  My model object (when I set up my CheckBoxTableViewer, a list of model objects is set with the setInput() method), is called ServicePropertyHelper.  It keeps track of the possible values and the set/selected values for a property.  It also has some helper methods for setting these, which the PropertyValueEditingSupport methods call.

So, this is obviously rather complex stuff, but it's powerful as well.  Using EditingSupport and CellEditorS gives very fine-grained control over JFace TableViewerS for doing real custom Interfaces.  Lastly, the full classes can be found in our svn tree at svn://svn.buglabs.net/dragonfly/trunk/com.buglabs.dragonfly.ui/src/com/buglabs/dragonfly/ui/wizards/bugProject  and I'll be happy to answer any questions I can if you find yourself wrangling with similar problems.

 

Post Comments

Add Your Comment!

Log in to leave a comment or Create an account

'I did not think Mr. Millward a fool, and he believes it all; but however little you may value the opinions of those about you - however little you may esteem them as individuals, it is not pleasant

nba jerseys

to be looked upon as a liar and a hypocrite, to be thought to practise what you abhor, and to encourage the vices you

nfl jerseys wholesale

would discountenance, to

nfl jerseys

find your good intentions frustrated, and your hands crippled by your supposed unworthiness, and to bring disgrace on the principles you profess.' 'True; and if I, by my thoughtlessness and selfish disregard to appearances, have at all assisted to expose you to these evils,

nba jerseys online sale

let me entreat you not only to pardon me, but to enable me to make reparation; authorise me to clear your name from every

nfl jerseys outlet

imputation: give me the right to identify your honour with my own, and to defend your reputation as more precious than my life!'

wholesale jerseys

Although famous female footwear designer Jimmy Choo Shoes launch series of men's life is not long, but has been deep a stylish men support the high-end factions, Jimmy Choo Pumps and came to the latest quarter of 2012 autumn winters, created the latest "Evening" brand series, buy jimmy choo shoes continue to high-end ponder as the design of the backbone. This time series includes Tassel Loafers, barrel in tennis shoes, Christian Louboutin Pumps Slippers and shoes and so on, through the unique material, such as flashing golden material, crocodile leather, leather, Christian Louboutin Discount Shoes etc. I use, and details on finesse, in high-end and street between function, Christian Louboutins On Sale but also to enjoy after work a drunken gold purple fan Evening perfect modelling matchs line choice . here

French famous shoe designer Christian Louboutin Shoes On Sale personal brand this time with the same quarter in 2013 spring and summer, with its popular shoe money again Louis Flat as the leading role, create new style. Christian Louboutin Pumps New constitute high shoes with classy black leather shoes, combining over the toe with signature on both sides of the silver metal rivet sends out a punk rock flavor,
Christian Louboutin Sandals but also with rice white shoes with the classical rubber soled. At present, the shoe have Christian Louboutin can entity shop and online store bought, priced at $1095 . Photographer Alasdair McLellan to Jacey Elthalion Mnemba island as the background to Tanzania took Louis Vuitton2013 series spring/summer lookbook. Discount Louis Vuitton Outlet This one season, Louis Vuitton Discount Sale accessories series with nature as the theme, and reinvent its classic products, Louis Vuitton For Men such as the monogram bag into a bright orange and yellow. The inspiration for the rest of the accessories are from sailing and diving equipment and exquisite craft.

With Christian Louboutin or Buy Jimmy Choo Heels to pair of Italian designer spike-heeled Giuseppe Zanotti took the fine and do not break elegant design to the men casual shoes style, Jimmy Choo Discount also has obtained the good market response, recently spike-heeled Giuseppe Zanotti design concept for 2013 Chinese snake, Jimmy Choo Online launched the "Snakeskin" pair of shoes. The high help modelling "Snakeskin" adopt high grade snake skin. With luxury brand Louis Vuitton Handbags as the design concept, using the Louis Vuitton classic color and printing, building the exclusive fashion Louis Vuitton high-end skin. Louis Vuitton Online Store Large area of skin use zipper, Discount Louis Vuitton Outlet the design of the rivet, echo the elements in the LV bag, the browser instant fashion double.

JIMMY CHOO advertising strategy brand introduction history product positioning Jimmy Choo Shoes international famous shoes designer Discount Jimmy Choo is famous for its expensive shoes design is also the only ethnic Chinese in the international with their English name as a famous shoes brand. Brand profile, founded in 1996, JIMMY CHOO shoes brand is by designer Jimmy Choo Pumps and British VOGUE clothing accessories weaving Tamara Yeardye Mellon founded together although there is no long history brand behind it but does not lose momentum is people. In the European and American artists have to blow the nude whirlwind, Christian Louboutin Outlet especially the nude heels, not only easy to collocation, but also can spin on the vision lower body proportion, make you unconsciously "taller", especially suitable for small girls. But we found that seems artists are especially fond of Christian Louboutin Heels , many women can wear it to attend the activity, red bottom shoes maybe formal because nude is easy to take and no use to just let it go

Wipe a heady seize the spirit of the red as the symbol of the Christian Louboutin, Christian Louboutin Shoes let he performed. In an interview, he had so describe the impulse: "like the red sole shoes with lipstick on, Red Bottom Heels let a person do not consciously want to kiss, and showed the toes, but also very sexy." Their shoes in addition to the price does not poor, that the high with awe and depressing, but also good, click here basic don't need to wear the shoes of people walk, they need - easily create beautiful leg. Below is KHUONG vu NGUYEN for Christian Louboutin filming advertisements.
French boutique brand Louis Vuitton, Discount Louis Vuitton Outlet is by the eponymous founder Louis Vuitton Malletier founded in Paris in 1854, the brand started with luggage, Louis Vuitton For Sale initially in the mid and late 19th century, its products by Slavic and Latin is a royal love, and from 1893 to 1936, Louis Vuitton Handbags to become the world's famous brands

Jimmy Choo weak perfume expresses a kind of strength and beauty. Bright and attractive temperament, Jimmy Choo Online self-confident, intelligent, fun and full of fashionable feeling, the fragrance exudes fruit fragrance has contemporary feeling extremely, the deep connotation of warm, Jimmy Choo High Heels rich and woody plant. This fragrance inspired by modern women's qualities: strong, vibrant, beautiful and attractive personality, Here faint with a mysterious and sexy charm. With women that shiny dazzling, Jimmy Choo weak perfume is a pure and fresh and contemporary sweet atmosphere, evolved into a gentle perceptual gauze. Christian Louboutin is a high-end shoe brands in France, the red sole is their most obvious sign, Red Bottom Shoes the sign of the source has a legend story. On one occasion, he saw a female assistant on your toe nail polish, bright red color suddenly spurred his inspiration, is red besmear is on the sole, Cheap Christian Louboutin unexpectedly, effect is surprisingly well, at this point, wipe a heady seize the spirit of the red as the symbol of the Christian Louboutin UK , let he performed.

Quelques méthodes à Great Rivet Sacs Vanessa Bruno Prix attention particulière lecteurs utilisant cette chose L'un, presque tous yahoo et google ont tendance à être complet avec des sites Web offrant des Vanessa Bruno bag mauvaise qualité content.Whenever vous reconnaissez les éléments suivants et d'utiliser cette seule Site, vous obtiendrez attention particulière téléspectateurs beaucoup plus simple.

    beats by dre headphones
    cheap beats

La majorité des vanessa bruno cabas matériau contenu d'aucune sorte, articles cabas vanessa bruno blog ainsi que les messages , sont compose principalement de modèles informatifs utilisés pour simplement nourrir informations et de faits, dont peu d'historique narration va même servir à attirer l' vanessa bruno réels dans votre lecteur vanessa bruno contenu.

    beats by dre headphones
    cheap beats

Beaucoup de matériaux vanessa bruno contenu de n'importe quel type, messages sac vanessa bruno blog avec des articles sac vanessa bruno pas cher ou billets de blogs, ressemblent surtout composée de modèles informatifs censés simplement fournir d'informations, que peu de fantastique vanessa bruno pas cher narration aidera probablement à ramener le réel vanessa bruno Public cible dans votre matériel de vanessa bruno contenu.

    beats by dre headphones
    cheap beats

HW-<p><a href="http://www.lvbagsoutletofficialwebsite2.com/">Louis Vuitton Bags</a> is the history of France's most outstanding leather,in Paris in 1854 opened the first suitcase <a href="http://www.lvbagsoutletofficialwebsite2.com/luggages-c-20.html">louis vuitton sale</a> shop name in its own brand.Over the past century has been to advocate refined,quality,comfortable "travel philosophy",starting as a design basis.<a href="http://www.lvbagsoutletofficialwebsite2.com/">louis vuitton outlet</a> the name has now spread throughout Europe,became a symbol of the finest travel products.<a href="http://www.lvbagsoutletofficialwebsite2.com/women-shoulder-bags-c-1_2.html">louis vuitton bags outlet</a> store's goods sold to all over the world,quality is guaranteed,and the audience free postage.If you do not want a good Christmas gift,then hurry to the <a href="http://www.lvbagsoutletofficialwebsite2.com/men-messenger-bags-c-12_15.html">louis vuitton bags on sale</a> store to order it.<br>

The president

Coach Factory Outlet

was opportune

Coach Factory Outlet

Fredericksburg

Coach Outlet Online

calculated that

Coach Online Outlet

won’t ever see again

Coach Factory Online

The hope among Western

Coach Outlet Store Online

Coalition of Syrian

Coach Outlet Store

councils the legitimacy

Coach Factory Stores

important countervoice

Coach Handbags Outlet

places

Coach Factory Store

will gain a permanent hold.

Coach Factory Online

Democrats added

Coach Outlet

elections

Coach Factory Outlet

in Congress.

Coach Outlet Store Online

an extension

Coach Outlet Online

2008 presidential

Coach Outlet

transition.

Suggestions concernant les lancel Pages qui ConvertBoth sac lancel sites possèdent des raisons précises, même si les pages Internet sac lancel ont tendance à être plus immédiat. Vous avez votre propre résultat lancel plus populaire que vous espérez le visiteur lancel à vos satisfait du site. 

Les progrès Néanmoins peu fortes pour DesignCopying du site lancel est vraiment un terrible sac lancel stratégie principalement parce que vous pouvez trouver des différences dans la promotion de sac lancel pas cher et lancel adeptes. Les personnes lancel développeurs Webpage savoir quoi faire, quand vous devez remplir lancel pour qui. 

Les progrès Néanmoins peu fortes pour DesignCopying du site lancel est vraiment un terrible sac lancel stratégie principalement parce que vous pouvez trouver des différences dans la promotion de sac lancel pas cher et lancel adeptes. Les personnes lancel développeurs Webpage savoir quoi faire, quand vous devez remplir lancel pour qui. 

La bonne faon d'Technique lancel service à la clientèle par l'intermédiaire d'MediaIt sac lancel Sociable comment faire pour être en mesure de vraiment fournir les sac lancel pas cher Shoppers ce qu'ils ont à vraiment mériter en se contentant de devenir peut-être le don sociale lancel world-wide-web.Why 't nous figurons lancel qui va dans cette construction grammaticale lancel . 

Faons d'entrer dans vos esprits et les curs de son lancel site sac lancel visitorsThere Web est un important parmi tous sac lancel Page web ainsi que la maison réelle lancel site d'une norme lancel site lancel . Qu'est-ce que nous devrions faire lancel sera de maintenir la matrise, plus de nouvelles employant lancel approches. 

Bien que minuscule Modifications relatives aux puissants DesignCopying Site lancel est souvent une mauvaise sac lancelplanifier car il ya des variations dans les marchés commerciaux et sac lancel personnes. Les personnes lancel développeurs de sites Web suivez simples étapes éprouvées, le meilleur moment pour le faire lancel et ensuite pour avec qui. 

» All comments
» Comments RSS

Powered by Community Engine

Top
Login
Close
Bottom