SWT Communicate between Child shell and parent shell takes time - java

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;
}

Related

javafx: bug when trying to close window properly

I am designing the close window functionality for my desktop application. A high level explanation of the functionality is listed:
If I click the Exit menuItem, it prompts a ConfirmBox the user to confirm whether he wants to save or not before closing the application.
If the user click on the CloseButton on the window to force close the window (i.e. setOnCloseRequest function), the Exit menuItem event is fire off, which brings the user to case (1) again.
Within my ConfirmBoxcode, I have bind ENTER key to save things, N key to not save things and ESCAPE key to close confirmBox.
I have also set accelerator for the Exit menuItem (METAKEY + E).
Everything works fine. However, there is a minor bug if I follow this special sequence of steps. Whenever I use the accelerator for the Exit menuItem (i.e. METAKEY + E) and then I press either one of the 3 keys(ENTER, ESCAPE, N), the confirmBox closes but it pops up again.
I am wondering why is this happening only in this very special case?
public class ConfirmBox {
// answer[0] determines the need to Save
// answer[1] determines whether to close the application or not
private static boolean[] answer = new boolean[]{false,false};
private static Stage window;
public static boolean[] displayWarning(String title, String message){
window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle(title);
window.setMinWidth(300);
Label label = new Label();
label.setText(message);
Button yesButton = new Button("Yes");
Button noButton = new Button("No");
// needToSave = true, close Application = true and close this confirmbox
yesButton.setOnAction(ey ->{
answer[0] = true;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = true and close this confirmbox
noButton.setOnAction(en -> {
answer[0] = false;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = false and close this confirmbox
window.setOnCloseRequest(e -> {
answer[0] = false;
answer[1] = false;
closeConfirmBox();
});
// key binding
window.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if ( e.getCode() == KeyCode.N){
noButton.fire();
e.consume();
}
});
// bind enter key to yesButton
window.addEventHandler(KeyEvent.KEY_PRESSED, ev -> {
if (ev.getCode() == KeyCode.ENTER ){
yesButton.fire();
ev.consume();
}
});
window.addEventFilter(KeyEvent.KEY_PRESSED, ev ->{
if(ev.getCode()==KeyCode.ESCAPE){
ev.consume();
answer[0] = false;
answer[1] = false;
closeConfirmBox();
}
});
VBox layout = new VBox(20);
layout.setPadding(new Insets(20,5,20,5));
HBox bottomLayout = new HBox(50);
bottomLayout.setPadding(new Insets(20,5,20,5));
bottomLayout.getChildren().addAll(yesButton,noButton);
bottomLayout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(label,bottomLayout);
layout.setAlignment(Pos.CENTER);
Scene scene = new Scene(layout);
window.setScene(scene);
window.showAndWait();
return answer;
}
public static void closeConfirmBox(){
window.close();
}
}
Within my controller class, this is how I designed my MenuItem menuItemExit.
menuItemExit.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
//System.out.println("set stage" + primaryStage);
boolean[] answer;
boolean needToSave = false;
boolean closeApplication = false;
if(saved.get() == false){
answer = ConfirmBox.displayWarning("Warning", "Do you want to save your stuff?");
needToSave = answer[0];
closeApplication = answer[1];
}
if(needToSave == true){
menuItemSave.fire();
}
if(closeApplication== true){
Platform.runLater(new Runnable() {
public void run() {
close();
}
});
}
}
});
primaryStage.setOnCloseRequest(e -> {
e.consume();
menuItemExit.fire();
});
menuItemExit.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.META_DOWN));
public void close(){
this.primaryStage.close();
}

how to delete selected rows (multiple rows) from CheckboxTableViewer when button clicks? (table is connected to oracle database)

i hava a CheckboxTableViewer which has 10 columns, and the table is filled from database,
and i have a button outside the table named as "Delete",
what i want to do is:-
when i select rows using check box (multiple selection also) and when i press the "delete" button , i want the selected rows should get deleted from the database, and the tableviewer shuold get refreshed.
am pasting my tableviewer code below:-
final CheckboxTableViewer dataTable = CheckboxTableViewer.newCheckList(TableComposite2, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.BORDER |SWT.DM_FILL_BACKGROUND|SWT.FULL_SELECTION);
dataTable .getTable().setHeaderVisible(true);
dataTable .getTable().setLinesVisible(true);
dataTable .setContentProvider(new ArrayContentProvider());
//Action Check box
TableColumn columnCHead=new TableColumn(dataTable .getTable(),SWT.NONE);
columnCHead.setText("Delete");
columnCHead.setWidth(50);
// setting column input
TableViewerColumn columnC=new TableViewerColumn(dataTable ,columnCHead);
columnC.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
return null;
}
});
TableColumn columnFS1Head=new TableColumn(dataTable .getTable(),SWT.NONE);
columnFS1Head.setText("SOURCE DIRECTORY");
columnFS1Head.setWidth(300);
TableViewerColumn columnFS1=new TableViewerColumn(dataTable ,columnFS1Head);
columnFS1.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
AgedFileMaster a=(AgedFileMaster)Element;
return a.getDIRECTORY_PATH();
}
enter code here});
......
and i have a button for delete operation,(outside the table),
when i press delete button, i want the selected rows to get deleted...
am beginner to SWT.
anyone please help......
Use addSelectionListener on your Button control to be notified when the button is pressed:
button.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
// TODO handle delete here
}
});
You need to do two things to remove the data - first update your data model to remove the objects and secondly tell the table viewer that the model has changed.
You can do something like this:
dataTable.getTable().setRedraw(false); // Stop redraw during update
IStructuredSelection selection = (IStructuredSelection)dataTable.getSelection();
for (Iterator<?> iterator = selection.iterator(); iterator.hasNext(); )
{
Object selectedObject = iterator.next();
// TODO remove from data model array
// Tell table view the object has been removed
dataTable.remove(selectedObject);
}
dataTable.getTable().setRedraw(true); // Allow updates to be drawn
An alternative to calling dataTable.remove on each object is to call dataTable.refresh once at the end. There is also a variant of remove which accepts an array of objects.
TableViewerColumn actionsNameCol = new TableViewerColumn(viewer, column);
actionsNameCol.setLabelProvider(new ColumnLabelProvider(){
//make sure you dispose these buttons when viewer input changes
Map<Object, Button> buttons = new HashMap<Object, Button>();
#Override
public void update(ViewerCell cell) {
TableItem item = (TableItem) cell.getItem();
Button button;
if(buttons.containsKey(cell.getElement()))
{
button = buttons.get(cell.getElement());
}
else
{
button = new Button((Composite) cell.getViewerRow().getControl(),SWT.NONE);
button.setText("Remove");
buttons.put(cell.getElement(), button);
}
TableEditor editor = new TableEditor(item.getParent());
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(button , item, cell.getColumnIndex());
editor.layout();
}
});
Delete selected rows (multiple rows) from Table when button clicks (Database Connectivity)
//Java ArrayList class uses a dynamic array for storing the elements
List<String> id_list=new ArrayList<String>();
//Button Text:Selected Row Delete
Button btnNewButton = new Button(parent, SWT.NONE);
btnNewButton.setText("Selected Row Delete");
btnNewButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
TableItem[] item=table.getItems();
for(int i=0;i<table.getItemCount();i++)
{
if(item[i].getChecked()&&!item[i].getText(1).equals(""))
{
String id=item[i].getText(1);
id_list.add(id);//Add ID into List
}
}
for(int j=0;j<id_list.size();j++)
{
//class:Test
//Method:DeleteData(String ID) pass id to delete rows
// type cast object into string
Test.DeleteData((String) id_list.get(j));
}
}
});
btnNewButton.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/delete.png"));
btnNewButton.setBounds(18, 370, 68, 23);
Test.java
public class Test {
static Connection conn = null;
static PreparedStatement presta=null;
public static void DeleteData(String ID)
{
String url = "jdbc:sqlite:Demo.db";
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(url);
presta = conn.prepareStatement("delete from Student where sid=?");
presta.setString(1, ID);
presta.executeUpdate();
DisplayData();
}catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}//End DeleteData()
}//End Test class

How to combine and validate two text fields for a swt dialog?

i have another question. I use a ModifyListener for one textfield to activate and deactivate the OK-Button in a swt dialog. It works great.
Now I want to add a ModifyListener for another textfield. I want that the OK-Button only is activated if in both text fields is min one char.
This is the code of the two fields:
descriptionText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
Text text = (Text) e.widget;
if (text.getText().length() == 0) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
if (text.getText().length() >= 1) {
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
});
}
the second field:
ccidText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
Text text = (Text) e.widget;
if (text.getText().length() == 0) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
if (text.getText().length() >= 1){
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
});
}
I know that it doesn´t work because there are no dependencies between the two buttons.
How can i combine it?
I want to set the ok-button false while both modifylistener detect a char.
If i delete all chars in one testfield the button must be deactivated again.
Thank u.
You can use the same Listener for both Text fields and add it for SWT.KeyUp:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout(SWT.VERTICAL));
final Text first = new Text(shell, SWT.BORDER);
final Text second = new Text(shell, SWT.BORDER);
final Button button = new Button(shell, SWT.PUSH);
button.setText("disabled");
button.setEnabled(false);
Listener listener = new Listener()
{
#Override
public void handleEvent(Event e)
{
String firstString = first.getText();
String secondString = second.getText();
button.setEnabled(!isEmpty(firstString) && !isEmpty(secondString));
button.setText(button.isEnabled() ? "enabled" : "disabled");
}
};
first.addListener(SWT.KeyUp, listener);
second.addListener(SWT.KeyUp, listener);
shell.pack();
shell.setSize(300, shell.getSize().y);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static boolean isEmpty(String input)
{
if(input == null)
return true;
else
return input.trim().isEmpty();
}
Looks like this:
The code will basically (on each key stroke) check if both Texts are empty. If so, disable the Button, else enable it.

Enter Key Listener for Date is not working in linux flavours

Here is my full coding.I have Two class firstone MyDateTime and Second one is Employee.
i have included currently working coding of mine.For the EmployeePart class,AbstractEditorPart is our own parent class Which is extended
public class MyDateTime extends DateTime{
public DateTime(Composite parent, int style)
{
super(parent, style);
}
public Date getValue()
{
Date date = new Date(getYear(), getMonth(), getDay());
return date;
}
}
public Class EmployeePart extends AbstractEditorPart(
private MyDateTime currentDate;
public void createBody(Composite parent){
currentDate=Util.createDateChooserCombo(parent, toolkit, "Date:", 2);
}
public void save(Employee input){
return null;
}
}
}
Turns out to be a little more complicated than I first thought.
One solution is to define a TabList for the Composite that contains your Widgets.
This way you can first define in which order you want them to be traversed.
Then add a Listener to each of the Widgets you want to traverse. This Listener will determine the next item in the TabList and force the focus on this item when either Tab or Enter is pressed.
Here is some example code:
public static void main(String[] args)
{
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite content = new Composite(shell, SWT.NONE);
content.setLayout(new FillLayout());
Text first = new Text(content, SWT.BORDER);
Text second = new Text(content, SWT.BORDER);
content.setTabList(new Control[] {first, second});
Listener enterListener = new Listener()
{
#Override
public void handleEvent(Event event)
{
/* Is it a traverse via Tab or Enter? */
if(event.keyCode == SWT.CR || event.keyCode == SWT.TRAVERSE_RETURN || event.keyCode == SWT.TRAVERSE_TAB_NEXT)
{
/* Get source of event */
Widget source = event.widget;
/* Get traverse order of content composite */
Control[] tabList = content.getTabList();
/* Try to find current position in the tab list */
for(int i = 0; i < tabList.length; i++)
{
if(source.equals(tabList[i]))
{
/* Get the next item in the tab list */
Control nextControl = tabList[(i + 1) % tabList.length];
/* And force the focus on this item */
nextControl.setFocus();
nextControl.forceFocus();
return;
}
}
}
}
};
first.addListener(SWT.KeyUp, enterListener);
second.addListener(SWT.KeyUp, enterListener);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}

Adding buttons to a table (java swt)

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.

Categories

Resources