I'm trying to replicate a UI similar to this:
http://librixxxi.blogspot.com/2011/06/punch-clock-021-and-clickable-edit.html
and I have been following the authors instructions (without success) on how to create buttons that are in each column of my table. The difference between my project as his is I am trying to use a Tree rather than a Table, and I am doing it in the context of an eclipse TreeViewer plugin. In theory it seems the implementation should be straightforward, but I can't seem to get it to work.
Here is my code, it is easily replicate-able as it is just the sample Java PDT sampleview with a treeviewer, plus a dozen or so extra lines in the createPartControl. Everything you don't see here is just the same as the sample:
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int i) {
if(i == 0){
return obj.toString();
}
return "";
}
public Image getColumnImage(Object obj, int i) {
if(i == 0){
String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
if (obj instanceof TreeParent)
imageKey = ISharedImages.IMG_OBJ_FOLDER;
return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
}
return null;
}
}
class NameSorter extends ViewerSorter {
}
/**
* The constructor.
*/
public ButtonView() {
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
Tree tree = viewer.getTree();
tree.setLinesVisible(true);
tree.setHeaderVisible(true);
TreeColumn column1 = new TreeColumn(tree, SWT.LEFT);
column1.setText("Name");
column1.setWidth(400);
TreeColumn column2 = new TreeColumn(tree, SWT.LEFT);
column2.setText("Some info");
column2.setWidth(300);
// Button experimentation
TreeItem[] items = tree.getItems();
for(int i = 0; i < items.length; i++){
TreeEditor editor = new TreeEditor(tree);
TreeItem item = items[i];
Button button = new Button(tree, SWT.PUSH);
button.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
button.setSize(16,16);
button.pack();
editor.horizontalAlignment = SWT.RIGHT;
editor.setEditor(button, item);
}
drillDownAdapter = new DrillDownAdapter(viewer);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(getViewSite());
// Create the help context id for the viewer's control
PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "ButtonTest.viewer");
makeActions();
hookContextMenu();
hookDoubleClickAction();
contributeToActionBars();
}
When you say that you can't seem to get it to work, do you mean that you can't see the buttons in your Tree?
The javadoc of the SWT TreeEditor class gives an example of a tree editor stating that
"The editor must have the same size as the cell and must not be any smaller than 50 pixels."
The following lines assure that these conditions are met in the example:
editor.grabHorizontal = true;
editor.minimumWidth = 50;
So if you add these lines to your editor the buttons should be visible.
[Edit: What I did to reproduce the behaviour]
I used the standard RCP Mail Example project and added your "Button experimentation" code to it. Inside, I used simple text buttons.
public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(createDummyModel());
experiment();
}
private void experiment() {
// Button experimentation
Tree tree = viewer.getTree();
TreeItem[] items = tree.getItems();
for(int i = 0; i < items.length; i++){
TreeEditor editor = new TreeEditor(tree);
TreeItem item = items[i];
Button button = new Button(tree, SWT.PUSH);
button.setText("A");
button.setSize(16,16);
button.pack();
editor.horizontalAlignment = SWT.RIGHT;
editor.grabHorizontal = true;
editor.minimumWidth = 50;
editor.setEditor(button, item);
}
}
When I execute the code like this, the buttons show up. When I comment out the lines setting the editor's grabHorizontal and minimumWidth values, the normal tree cell renderer is shown and the buttons are not visible.
Related
I'm sadly far from being an expert in SWT and RCP, but I really tried my best here... I can't figure out how to configure the widgets to get this layout (just a Photoshopped screen, never worked this way):
This is what I get if I set the column number of the GridLayout to 2:
Here is the Refresh and the Blacklist button in the wrong row, but at least everything is visible...
And this is what I get if I set the column number of the GridLayout to 3:
This is total messed up... Most of the widgets are pushed outside the visible area. DatePicker, Refresh, Whitelist and the Calculate buttons are not visible, they are somewhere outside on the right.
This is the codepart for this screen area:
resultingProductsGroup = new Group(propProdGroup, SWT.NONE);
final GridData gd_resultingProductsGroup = new GridData(SWT.FILL,
SWT.CENTER, true, false);
gd_resultingProductsGroup.widthHint = 240;
resultingProductsGroup.setLayoutData(gd_resultingProductsGroup);
resultingProductsGroup.setText("Resulting products");
final GridLayout gridLayout_4 = new GridLayout();
gridLayout_4.numColumns = 2;
resultingProductsGroup.setLayout(gridLayout_4);
Label refDateLabel = new Label(resultingProductsGroup, SWT.NONE);
refDateLabel.setText("Reference date:");
refDateInput = new DateInput(resultingProductsGroup, SWT.BORDER);
refDateInput.setLayoutData(new GridData());
refDateInput.setValue(new Date());
calculateProductsButton1 = new Button(resultingProductsGroup, SWT.NONE);
setupImageButton(calculateProductsButton1, Images.getButtonRefresh());
calculateProductsButton1.setLayoutData(new GridData());
GridDataFactory.swtDefaults().hint(18, 18).applyTo(
calculateProductsButton1);
resultingProductsTable = new TableListWidget<Product>(
resultingProductsGroup, SWT.BORDER, ListWidgetMode.MULTI);
resultingProductsTable.setLinesVisible(true);
resultingProductsTable.setHeaderVisible(true);
final GridData rpTableProperty = new GridData(SWT.FILL, SWT.FILL, true,
true, 3, 1);
resultingProductsTable.setLayoutData(rpTableProperty);
GridDataFactory.swtDefaults().hint(230, 240).applyTo(
resultingProductsTable);
setupResultingProductsTableColumns();
resultingProductsTable.sortByComparator(new Comparator<Product>() {
#Override
public int compare(Product o1, Product o2) {
return o1.getPartNum().getExternalId().compareTo(
o2.getPartNum().getExternalId());
}
});
resultingProductsTable.addOpenListener(new IOpenListener() {
#Override
public void open(OpenEvent event) {
doResultingProductsTableOpen();
}
});
calculateProductsButton2 = new Button(resultingProductsGroup, SWT.NONE);
calculateProductsButton2.setText("Calculate");
whitelistAddButton = new Button(resultingProductsGroup, SWT.NONE);
whitelistAddButton.setText("Whitelist");
whitelistAddButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(final SelectionEvent e) {
doAddToWhitelist();
}
});
blacklistAddButton = new Button(resultingProductsGroup, SWT.NONE);
blacklistAddButton.setText("Blacklist");
blacklistAddButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(final SelectionEvent e) {
doAddToBlacklist();
}
});
What am I not seeing here? I'm stuck with this GUI bug for over 2 days now... Please, help me :)
You could design the whole composite with one GridLayout and 3 columns, while using horizontal span of 3 on the table. That doesn't give you the desired mocked up screen though, because reference date controls and buttons at the bottom would be aligned in columns.
Try instead using 3 composites
reference date: row layout
table: fill layout
button list: row layout
In order for the end-user to constrain a search to some columns of the main TableView, I needed a treeview with checkboxes.
I decided to embed this TreeView in a popup, showing on click on a custom button.
I have created the following class, inspired from the question:
Java FX8 TreeView in a table cell
public class CustomTreeMenuButton extends MenuButton {
private PopupControl popup = new PopupControl();
private TreeView<? extends Object> tree;
private CustomTreeMenuButton me = this;
public void setTree(TreeView<? extends Object> tree) {
this.tree = tree;
}
public CustomTreeMenuButton() {
super();
this.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (!popup.isShowing()) {
Bounds b = me.localToScreen(me.getBoundsInLocal());
double x = b.getMinX();
double y = b.getMaxY();
popup.setAutoHide(true);
// popup.setAutoFix(true);
popup.setAnchorX(x);
popup.setAnchorY(y);
popup.setSkin(new Skin<Skinnable>() {
#Override
public void dispose() {
}
#Override
public Node getNode() {
return tree;
}
#Override
public Skinnable getSkinnable() {
return null;
}
});
popup.show(me.getScene().getWindow());
}
}
});
}
}
The tree I am working with contains CheckBoxTreeItem objects, and while the popup is working, there is some weird blur on all checkboxes, whenever the focus is not on a checkbox. (See GIF below)
First, I was thinking it was maybe an antialiasing problem, but popup.getScene().getAntiAliasing().toString() returns DISABLED
Then, I saw that non integer anchor points could cause problems. However popup.setAutoFix(true) did nothing, nor did the following:
popup.setAnchorX(new Double(x).intValue());
popup.setAnchorY(new Double(y).intValue());
It might be worth noting that I am working with FXML.
How can I get sharp checkboxes regardless of their focus ?
I would suggest a built-in control, CustomMenuItem, rather than reinventing the wheel:
A MenuItem that allows for arbitrary nodes to be embedded within it,
by assigning a Node to the content property.
An example
// Create the tree
CheckBoxTreeItem<String> rootItem = new CheckBoxTreeItem<String>("All stuff");
rootItem.setExpanded(true);
final TreeView<String> tree = new TreeView<String>(rootItem);
tree.setEditable(true);
tree.setCellFactory(CheckBoxTreeCell.<String>forTreeView());
for (int i = 0; i < 8; i++) {
final CheckBoxTreeItem<String> checkBoxTreeItem =
new CheckBoxTreeItem<String>("Stuff" + (i+1));
rootItem.getChildren().add(checkBoxTreeItem);
}
tree.setRoot(rootItem);
tree.setShowRoot(true);
// Create a custom menu item
CustomMenuItem customMenuItem = new CustomMenuItem(tree);
customMenuItem.setHideOnClick(false);
// Create the menu button
MenuButton mb = new MenuButton("Stuffs");
mb.getItems().add(customMenuItem);
And the output
Note: It is important to set the hideOnClickProperty to true, to avoid closing when the user clicks in the tree, which can be even done in the contructor, so you can shorten the initialization to:
CustomMenuItem customMenuItem = new CustomMenuItem(tree, false);
If you want to remove the hover glow, you can add the following CSS class:
.menu-item {
-fx-padding: 0;
}
We are using a OTB Application called Teamcenter. I am writing a add on application that is invoked from a menu selection in the Teamcenter Application.
When they click the menu item, that executes a handler class and that creates the base dialog for my application.
It will Show Selected Component from Teamcenter on Open dialog .
Dialog has One text field with Button.
User go back to parent window and select item and then click button on dialog this will set selected item on opened dialog.
But When Dialog open and i go back to parent i.e OTB teamcenter application for selecting item it takes time it looks like it got hanged.
Note:
Text Button
List
text and button are adjacent field.
If user select 1200 parts and goto menu and select item then it will show popup and then click on parent window for single item selection,clicking on parent takes time
but if we have 200 parts and then go back and click on parent window it doesn't take much time
Can anyone please suggest how to improve time performance ?
// open( ) : First Call on Menu selection will call open() method
//setSourceBomLinesOnSessionInfo() :Call from Open method() to set Required selected item information in session required to be set on Dialog List component
// SetScope() :Set text data on button selection on opened dialog
// user will go on parent window and select item and then coming back on opened dialog and click button
public void open()
{
eQOTMLoggerManager.logger.debug("open 'OTM Compare' Dialog");
eQOTMSessionInfo.getInstance().clearCurrentSelection();
Shell prevShell = getOTMCompareDialog();
if (prevShell != null)
{
prevShell.setMinimized(false);
}else{
try{
//Set Source BomLine on OTM Dialog Window
bSetInputOnDialog = setSourceBomLinesOnSessionInfo();
if( bSetInputOnDialog )
{
initializeUIComponents();
mainDialogShell.open();
Display display = mainDialogShell.getDisplay();
while (!mainDialogShell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
mainDialogShell.dispose();
}
else if (mainDialogShell != null)
{
mainDialogShell.dispose();
}
eQOTMLoggerManager.logger.error("INFO:Exit initialize UI Components for OTM compare dialog.");
}
catch (Throwable th)
{
eQOTMLoggerManager.logger.error("Exception occurred while initializing UI Components for OTM compare dialog. Error: "+th.getMessage(),th);
}
}
}
//Initialize UI Component
private void initializeUIComponents() throws TCException
{
eQOTMLoggerManager.logger.error("INFO:In initialize UI Components for OTM compare dialog !!!");
mainDialogShell = new Shell(this.m_parentShell, SWT.DIALOG_TRIM |SWT.MODELESS);
mainDialogShell.setText(this.m_sOTMDialogTitle);
mainDialogShell.setLocation(getParent().toDisplay(300, 200));
mainDialogShell.setSize(450, 400);
/* Image dialogicon = new Image(mainDialogShell.getDisplay(),"icon/ecubeIcon.png");
mainDialogShell.setImage(dialogicon);
*/
/*Main grid*/
GridLayout gridLayout = new GridLayout(4, false);
gridLayout.verticalSpacing = 10;
mainDialogShell.setLayout(gridLayout);
//Scope label to display on UI
new Label(mainDialogShell, SWT.NONE|SWT.CENTER).setText("Scope:");
//Text filed for scope
this.m_textScopeName = new Text(mainDialogShell,SWT.READ_ONLY|SWT.SINGLE | SWT.BORDER);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
this.m_textScopeName.setLayoutData(gridData);
//Button to set scope
Button btnsetscope = new Button(mainDialogShell, SWT.PUSH);
btnsetscope.setText("Set Scope");
gridData = new GridData();
gridData.horizontalSpan = 1;
gridData.horizontalAlignment = GridData.END;
btnsetscope.setLayoutData(gridData);
//Label for List of Parts to Compare
new Label(mainDialogShell, SWT.NONE).setText("List of Parts to Compare :");
//Text filed for List of Parts to Compare
m_listKitParts = new Text(mainDialogShell, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL
| SWT.V_SCROLL);
gridData = new GridData(GridData.FILL, GridData.FILL, true, true);
gridData.horizontalSpan = 3;
gridData.grabExcessVerticalSpace = true;
m_listKitParts.setLayoutData(gridData);
final Button btnCompare = new Button(mainDialogShell, SWT.PUSH);
btnCompare.setText("Identify");
gridData = new GridData();
gridData.horizontalSpan = 3;
gridData.horizontalAlignment = GridData.END;
btnCompare.setLayoutData(gridData);
final Button btnCancel = new Button(mainDialogShell, SWT.PUSH);
btnCancel.setText(" Cancel ");
gridData = new GridData();
gridData.horizontalSpan = 1;
gridData.horizontalAlignment = GridData.END;
btnCancel.setLayoutData(gridData);
long start_time = System.nanoTime();
/*
TCComponentBOMLine[] alSelectedSRCBOMLinetemp = eQOTMSessionInfo.getInstance().getCurrentSourceBOMLines();
int componentsize=alSelectedSRCBOMLinetemp.length;
for(int i=0;i<componentsize;i++)
{
m_listKitParts.append(alSelectedSRCBOMLinetemp[i].toString()+"\n");
}
*/
InterfaceAIFComponent selectedcomponent[]=m_sourcepanel.getSelectedComponents();
int componentsize=selectedcomponent.length;
for(int i=0;i<componentsize;i++)
{
m_listKitParts.append(selectedcomponent[i]+"\n");
}
long end_time = System.nanoTime();
double difference = (end_time - start_time)/1e6;
eQOTMLoggerManager.logger.error("INFO:Response return to TC. Total time taken: "+(difference)/1000);
//Set scope Button Listener
btnsetscope.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
//Set Scope for Compare BOMLine operation
SetScope();
}
});
//Compare Button Listener
btnCompare.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
if(m_textScopeName.getText().length()<=0)
{
m_textScopeName.setFocus();
MessageBox.post(Messages.eQOTM_ScopeSelection_info,Messages.eQOTM_ScopeSelection_title, 2);
}
else
{
btnCompare.setEnabled(false);
btnCancel.setEnabled(false);
Job serverJob = new Job(eQOTMConstants.Stausmessage)
{
protected IStatus run(IProgressMonitor monitor)
{
eQOTMLoggerManager.logger.error("INFO:Started backgound thread to call MI process\n");
compareBOMLines();
mainDialogShell.getDisplay().syncExec(new Runnable()
{
public void run()
{
mainDialogShell.close();
}
});
return Status.OK_STATUS;
}
};
serverJob.setPriority(Job.SHORT);
serverJob.schedule();
}
}
});
//cancel Button Listener
btnCancel.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
mainDialogShell.close();
}
});
eQOTMLoggerManager.logger.error("INFO:Exit initialize UI Components for OTM compare dialog.");
}
private boolean setSourceBomLinesOnSessionInfo() throws TCException
{
eQOTMLoggerManager.logger.debug("In setSourceBomLinesOnCompareDialog");
InterfaceComparable sourcePanel = m_currentTcApplication.getActiveComparable();
eQOTMSessionInfo objOTMSession = eQOTMSessionInfo.getInstance();
this.m_sourcepanel=sourcePanel;
TCComponentBOMLine[] arrayOfTargetTCComponentBOMLine = null;
ArrayList<TCComponentBOMLine> arrlcheckedBOMLine = new ArrayList<TCComponentBOMLine>();
if(((BOMTreeTable)sourcePanel.getCompareTreeTable()).getBOMWindow().getTopBOMLine().getDisplayType().toString().equals(eQOTMConstants.IS_MFG_PLAN))
{
if( !SetScope() )//on error return false
return false;
if( !setCheckedBomlines(arrlcheckedBOMLine)){//on error return false
return false;
}
arrayOfTargetTCComponentBOMLine = (TCComponentBOMLine[])arrlcheckedBOMLine.toArray(new TCComponentBOMLine[arrlcheckedBOMLine.size()]);
}else
{
//EBOM Install to -EBOM Install /MBOM kit to EBOM install Comparison
arrayOfTargetTCComponentBOMLine = ((BOMTreeTable)sourcePanel.getCompareTreeTable()).getSelectedBOMLines();
}
if ( arrayOfTargetTCComponentBOMLine == null || arrayOfTargetTCComponentBOMLine.length == 0)
{
MessageBox.post(Messages.eQOTM_KitSelection_info,Messages.eQOTM_KitSelection_title, 2);
return false;
}
objOTMSession.setCurrentSourceBOMLines(arrayOfTargetTCComponentBOMLine);
eQOTMLoggerManager.logger.error("INFO:No. of Bomlines selected for comparison : "+arrayOfTargetTCComponentBOMLine.length);
eQOTMLoggerManager.logger.debug("Exit setSourceBomLinesOnCompareDialog");
return true;
}
private boolean SetScope()
{
InterfaceComparable targetPanel = m_currentTcApplication.getActiveComparable();
eQOTMSessionInfo objOTMSession = eQOTMSessionInfo.getInstance();
objOTMSession.setTargetBOMTreeTable((BOMTreeTable)targetPanel.getCompareTreeTable());
try
{
objOTMSession.addUserSessionVariable(eQOTMConstants.REVISIONRULE,((BOMTreeTable)targetPanel.getCompareTreeTable()).getBOMWindow().getRevisionRule().toString());
}
catch (Exception e)
{
eQOTMLoggerManager.logger.error("Error occurred while getting RevisionRule from TC user session. Error : "+e.getMessage(),e);
MessageBox.post(Messages.eQOTM_ScopeRevisionRule_info,Messages.eQOTM_ScopeSelection_title, 2);
return false;
}
TCComponentBOMLine[] arrayOfScopeTCComponentBOMLine = ((BOMTreeTable)targetPanel.getCompareTreeTable()).getSelectedBOMLines();
if( arrayOfScopeTCComponentBOMLine==null || arrayOfScopeTCComponentBOMLine.length<1 )
{
MessageBox.post(Messages.eQOTM_ScopeSelection_info,Messages.eQOTM_ScopeSelection_title, 2);
return false;
}
TCComponentBOMLine scopebomline = arrayOfScopeTCComponentBOMLine[0];
try
{
if (scopebomline.getChildrenCount() ==0)
{
MessageBox.post(Messages.eQOTM_ScopeNoChild_info,Messages.eQOTM_ScopeSelection_title, 2);
return false;
}
}
catch (TCException localTCException1)
{
eQOTMLoggerManager.logger.error("Exception Occurred while getting child count for scope");
}
this.m_textScopeName.setText(scopebomline.toString());
eQBOMLineBean currentScopeBOMLine = new eQBOMLineBean(scopebomline);
objOTMSession.setCurrentScopeBOMLine(currentScopeBOMLine);
return true;
}
I am working on Eclipse plugin. Here i created a separate view and now i want to format the color of tree node.
These are code present in createpartcontrol method.
ScrolledComposite sc = new ScrolledComposite(parent, SWT.V_SCROLL );
Composite composite1 = new Composite(sc, SWT.NONE);
Composite composite_1 = creatingcomposite(composite1);
Tree tree = new Tree(composite_1, SWT.FULL_SELECTION );
TreeItem item = new TreeItem(tree, SWT.NONE);
here i want to set some colour like blue.
item.setText("This is sparta");
Now here i want some different colour like yellow on subsubitem text.
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText(new String[] { "Function Name: "+ errorPreTest11.description.get(j).function });
For doing this i tried to set SWT.COLOR_BLUE but it's not working.
Use
item.setForeground(tree.getDisplay().getSystemColor(SWT.COLOR_BLUE));
You can also create your own colors but if you do this you must dispose of them when you are done.
I suggest you using the TreeViewer. In this case you would have a functionality to set a LabelProvier on your viewer. Label provider has a subclass called StyledCellLabelProvider, which you can successfully extend to provide styling of your labels like this: (Please also see a TextStyle class for more formating options).
public class MyStyledLabelProvider extends StyledCellLabelProvider {
private Styler defaultStyler;
public MyStyledLabelProvider () {
defaultStyler = new Styler() {
#Override
public void applyStyles(TextStyle textStyle) {
textStyle.strikeout = true;
}
};
}
#Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
StyledString styledString = getStyledString(element);
cell.setText(styledString.toString());
cell.setStyleRanges(styledString.getStyleRanges());
super.update(cell);
}
#SuppressWarnings("unchecked")
private StyledString getStyledString(Object element) {
return new StyledString("Cell string", defaultStyler);
}
}
Is it possible to always show the vertical scroll bar in a SWT table even if the table is empty? By always showing a (possible disabled) vertical scroll bar one can avoid that the last column get partially hidden when the columns use ColumnWeightData for layouting.
I tried to initialize the table with SWT.V_SCROLL or to use table.getVerticalBar().setVisible(true) - both without success.
There is a method setAlwaysShowScrollBars in ScrollableComposite. What I am looking for is a similar method in Table.
UPDATE: I suppose that the scroll bars which are visible when the table contains enough data are not those scroll bars which Table inherits from Scrollable. I have debugged ScrollBar.setVisible(boolean) and it seems not be called on table layout updates. Is this observation correct?
UPDATE 2: Here is a snippet for a table construction. It would be great to have the vertical scrollbar visible even if the table is empty and to have the column headers visible even if the table data are scrolled down. Note: The snippet has left out some details as the label provider and some other controls arranged at the same parent composite.
protected void createMasterPart(final IManagedForm managedForm, Composite parentComposite)
{
FormToolkit toolkit = managedForm.getToolkit();
Composite contentComposite = toolkit.createComposite(parentComposite, SWT.NONE);
contentComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
toolkit.paintBordersFor(contentComposite);
contentComposite.setLayout(new GridLayout(2, false));
GridData gd;
Composite tableComposite = new Composite(contentComposite, SWT.NONE);
TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3);
tableComposite.setLayoutData(gd);
speakerTableViewer = new TableViewer(tableComposite, SWT.BORDER | SWT.FULL_SELECTION);
speakerTableViewer.setContentProvider(ArrayContentProvider.getInstance());
Table speakerTable = speakerTableViewer.getTable();
speakerTable.setHeaderVisible(true);
speakerTable.setLinesVisible(true);
toolkit.paintBordersFor(speakerTable);
TableViewerColumn tableViewerAudiosampleColumn = new TableViewerColumn(speakerTableViewer, SWT.NONE);
TableColumn audiosampleColumn = tableViewerAudiosampleColumn.getColumn();
tableColumnLayout.setColumnData(audiosampleColumn, new ColumnWeightData(60, true));
audiosampleColumn.setText("Sample");
TableViewerColumn tableViewerSpeakerColumn = new TableViewerColumn(speakerTableViewer, SWT.NONE);
TableColumn speakerColumn = tableViewerSpeakerColumn.getColumn();
tableColumnLayout.setColumnData(speakerColumn, new ColumnWeightData(60, true));
speakerColumn.setText("Speaker");
TableViewerColumn tableViewerRemarkColumn = new TableViewerColumn(speakerTableViewer, SWT.NONE);
TableColumn remarkColumn = tableViewerRemarkColumn.getColumn();
tableColumnLayout.setColumnData(remarkColumn, new ColumnWeightData(120, true));
remarkColumn.setText("Remark");
}
It's not possible to force the Table to always show scroll bars, the OS decides when to show them.
Alternatives
Right, I came up with a solution very similar to my answer to this question:
Is it possible to get the vertical/horizontal scroll bar visible when the SWT List is in disabled state?
The idea is to use a ScrolledComposite (as the other answer already suggested) to take care of the scrolling. The Table itself won't scroll. However, this won't make any difference, because the user won't be able to tell the difference.
ScrolledComposite has a method called setAlwaysShowScrollBars(boolean) with which you can force it to always show the scroll bars, even if they aren't required.
Here is some sample code, that will illustrate what I just talked about:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
final ScrolledComposite composite = new ScrolledComposite(shell, SWT.V_SCROLL);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Table table = new Table(composite, SWT.NO_SCROLL | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
composite.setContent(table);
composite.setExpandHorizontal(true);
composite.setExpandVertical(true);
composite.setAlwaysShowScrollBars(true);
composite.setMinSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT));
Button fillTable = new Button(shell, SWT.PUSH);
fillTable.setText("Fill table");
fillTable.setLayoutData(new GridData(SWT.FILL, SWT.END, true, false));
fillTable.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event arg0)
{
if (table.getColumnCount() < 1)
{
for (int col = 0; col < 4; col++)
{
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText("Column " + col);
}
}
for (int row = 0; row < 20; row++)
{
TableItem item = new TableItem(table, SWT.NONE);
for (int col = 0; col < table.getColumnCount(); col++)
{
item.setText(col, "Item " + row + " " + col);
}
}
for (int col = 0; col < table.getColumnCount(); col++)
{
table.getColumn(col).pack();
}
composite.setMinSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
Button clearTable = new Button(shell, SWT.PUSH);
clearTable.setText("Clear table");
clearTable.setLayoutData(new GridData(SWT.FILL, SWT.END, true, false));
clearTable.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event arg0)
{
table.removeAll();
composite.setMinSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
shell.pack();
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Looks like this:
As you can see, the scroll bar is always visible.
UPDATE
As pointed out in the comment, this approach will not keep the Table headers visible when you scroll down. If you could post a small working code example that illustrates your problem, we might come up with an alternative (unrelated to forcing the scroll bars).
UPDATE2
Here is some code that should do what you want, the trick is to trigger a resize event on the parent of the TableViewer, the horizontal scrollbar that is shown isn't really necessary and it disappears after you resize the window:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new GridLayout());
createMasterPart(shell);
shell.pack();
shell.setSize(400, 300);
shell.open();
shell.layout(true, true);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static void createMasterPart(Composite parentComposite)
{
Composite composite = new Composite(parentComposite, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite.setLayout(new GridLayout(1, false));
Composite tableComposite = new Composite(composite, SWT.NONE);
TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableViewer tableViewer = new TableViewer(tableComposite, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableViewerColumn firstTableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn firstTableColumn = firstTableViewerColumn.getColumn();
firstTableColumn.setText("Sample");
firstTableViewerColumn.setLabelProvider(new ColumnLabelProvider()
{
#Override
public String getText(Object element)
{
Dummy p = (Dummy) element;
return p.first;
}
});
TableViewerColumn secondTableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn secondTableColumn = secondTableViewerColumn.getColumn();
secondTableColumn.setText("Speaker");
secondTableViewerColumn.setLabelProvider(new ColumnLabelProvider()
{
#Override
public String getText(Object element)
{
Dummy p = (Dummy) element;
return p.second;
}
});
TableViewerColumn thirdTableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn thirdTableColumn = thirdTableViewerColumn.getColumn();
thirdTableColumn.setText("Remark");
thirdTableViewerColumn.setLabelProvider(new ColumnLabelProvider()
{
#Override
public String getText(Object element)
{
Dummy p = (Dummy) element;
return p.third;
}
});
List<Dummy> elements = new ArrayList<>();
for(int i = 0; i < 20; i++)
{
elements.add(new Dummy("firstfirstfirst " + i, "secondsecondsecond " + i, "thirdthirdthirdthirdthirdthird " + i));
}
tableViewer.setInput(elements);
tableColumnLayout.setColumnData(firstTableColumn, new ColumnWeightData(1, true));
tableColumnLayout.setColumnData(secondTableColumn, new ColumnWeightData(1, true));
tableColumnLayout.setColumnData(thirdTableColumn, new ColumnWeightData(2, true));
}
private static class Dummy
{
public String first;
public String second;
public String third;
public Dummy(String first, String second, String third)
{
this.first = first;
this.second = second;
this.third = third;
}
}
I have created a solution that I think is better than put your table inside a ScrolledComposite.
My solution: fill my table with empty items until my scroll bar is visible.
Example:
// Flag that knows if the empty item was added or not
boolean addedEmptyItem = false;
// Get the table client area
Rectangle rect = table.getClientArea ();
// Get the item height
int itemHeight = table.getItemHeight ();
// Get the header height
int headerHeight = table.getHeaderHeight ();
// Calculate how many items can be visible without scrolling
int visibleCount = (rect.height - headerHeight + itemHeight - 1) / itemHeight;
while ( visibleCount > table.getItemCount() ) {
// Add an empty item
new TableItem( table, SWT.NONE );
// Set the flag
addedEmptyItem = true;
}
// Vertical bar é disabled if an empty item was added
table.getVerticalBar().setEnabled( !addedEmptyItem );
I hope this solution helps someone.
Thanks.
I don't think you can do this but you can try call ScrolledComposite.setAlwaysShowScrollbars() to true, but you will see both of the enabled scrollbars all the time.