Search code examples
javaswtjfacetableviewer

SWT - Table Viewer center checkbox


The last column of my Table Viewer contains a check box only. The check box appears in the left side of the cell, and because the column name is pretty long it looks ugly as hell. How can I center the check box in the middle of the cell ? Is it possible without using images ? Here is how I create the column:

    // third column - check box. temporary
    TableColumn column = new TableColumn(viewer.getTable(), SWT.NONE);
    column.setText("PrettyLongColumnName");
    column.setWidth(100);
    TableViewerColumn checkColumn = new TableViewerColumn(viewer, column);
    checkColumn.setLabelProvider(new ColumnLabelProvider() {
        // the checkboxes should be disposed and rebuilt when input changes
        @Override
        public void update(ViewerCell cell) {
            MyObject system = (MyObject) cell.getElement();
            TableItem item = (TableItem) cell.getItem();
            Button button;
            if (buttonsMap.containsKey(cell.getElement())) {
                button = rightTableButtons.get(cell.getElement());
            } else {
                button = new Button((Composite) cell.getViewerRow().getControl(), SWT.CHECK);
                button.setEnabled(true);                   
                buttonsMap.put(cell.getElement(), button);

                TableEditor editor = new TableEditor(item.getParent());
                editor.grabHorizontal = true;
                editor.grabVertical = true;
                editor.setEditor(button, item, cell.getColumnIndex());
                editor.layout();
                }
            }
        }
    });

Solution

  • TL;DR: Not available nativley, but can be implemented via epic hackery.

    Checkboxes are actually an OS feature. As SWT is cross-platform, we rely on it being provided by OS.

    AFIK the only thing provided by all OS's (Gtk/Win32/Cocoa) is a single checkbox on the first column. Other fancy functionality has to be implemented manually.

    One way I've seen people do it is to draw custom icons and then update the icon when you click on it with event listeners.

    One example on how to draw icons on the right is in this snippet. You'd have to add click listener to change the icon when clicked into checked/unchecked.

    Note, this may cause your application to look inconsistent across platforms and themes (e.g dark theme). To get around this, we have had some people that actually generate a native checkbox, then programatically take a screen shot, then draw it in the right side of a column. I think this is hackery at it's finest.

    Let me know if you have questions.