Save ViewPart on Exit - java

I am new in GEF & RCP. Now I want to Save my ViewPart on exit for that i have implemented savestate and init method. But I am using a tableItem to fill data in My viewpart. When I try to get text from my table and store them in my savestate nothing is happening. How can I save my data stored in TableItem from savestate and initialize when i start up my graphical editor
public class Theartview extends ViewPart implements Serializable {
private static final long serialVersionUID = -3033215443267698138L;
public static String ID = "TutoGEF.theartview_id";
public Text text;
public Text text_1;
private Table table;
private IMemento memento;
#SuppressWarnings("unused")
private Node node;
private static Node sourceNode;
private static Node targetNode;
private static int connectionType;
TableItem[] items = null;
#Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
this.memento = memento;
super.init(site, memento);
System.out.println("hi there");
}
#Override
public void saveState(IMemento memento) {
super.saveState(memento);
System.out.println("hello there");
}
#SuppressWarnings("static-access")
public void getDataOfConnection(Node sourceNode, Node targetNode,
int connectionType1) {
this.sourceNode = sourceNode;
this.targetNode = targetNode;
this.connectionType = connectionType1;
}
public Theartview() {
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(10, false));
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 10, 1));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tblclmnTheartName = new TableColumn(table, SWT.NONE);// 1
tblclmnTheartName.setWidth(100);
tblclmnTheartName.setText("Theart Name");
TableColumn tblclmnCategory = new TableColumn(table, SWT.NONE);// 2
tblclmnCategory.setWidth(100);
tblclmnCategory.setText("Category");
TableColumn tblclmnCombo = new TableColumn(table, SWT.NONE);// 3
tblclmnCombo.setWidth(100);
tblclmnCombo.setText("Satus");
TableColumn tblclmnCombo_1 = new TableColumn(table, SWT.NONE);// 4
tblclmnCombo_1.setWidth(100);
tblclmnCombo_1.setText("Priority");
TableColumn tblclmnDescription = new TableColumn(table, SWT.NONE);// 5
tblclmnDescription.setWidth(162);
tblclmnDescription.setText("Description");
TableColumn tblclmnJustification = new TableColumn(table, SWT.NONE);// 6
tblclmnJustification.setWidth(212);
tblclmnJustification.setText("Justification");
// getfillTableRoWData();
if (memento != null) {
restoreState(memento);
}
memento = null;
}
void restoreState(IMemento memento) {
}
public void fillTableRoWData() {
try {
if (Connection.Number_Of_Connection != 0) {
TableItem item = new TableItem(table, SWT.NONE);
String tempConType = null;
String sourceNodeName = null;
String targetNodeName = null;
String settingString = null;
for (int s = 1; s <= Connection.Number_Of_Connection; s++) {
if (connectionType == Connection.CONNECTION_DESIGN) {
tempConType = "Deliver Design";
} else if (connectionType == Connection.CONNECTION_RESOURCES) {
tempConType = "Deliver Resource";
} else if (connectionType == Connection.CONNECTION_WORKPACKAGES) {
tempConType = "Distributed Work Packages";
}
// for source
if (Service.class.isInstance(sourceNode)) {
sourceNodeName = "Service-";
} else if (Circle.class.isInstance(sourceNode)) {
sourceNodeName = "Circle-";
}
// for targets
if (Service.class.isInstance(targetNode)) {
targetNodeName = "Service ";
} else if (Circle.class.isInstance(targetNode)) {
targetNodeName = "Circle ";
}
if (sourceNodeName.equals(targetNodeName)) {
settingString = sourceNodeName + tempConType;
} else if (!(sourceNodeName.equals(targetNodeName))) {
settingString = sourceNodeName + targetNodeName
+ tempConType;
}
for (int j = 0; j < 6; j++) {
TableEditor editor = new TableEditor(table);
Text text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 0);
text.setText(settingString);
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 1);
text.setText(settingString);
editor = new TableEditor(table);
Combo Status_Combo = new Combo(table, SWT.NONE);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
Status_Combo.setText("Not Started");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
editor = new TableEditor(table);
Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
priority_Combo.setText("High");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 4);
text.setText(settingString);
editor = new TableEditor(table);
text = new Text(table, SWT.MULTI | SWT.BORDER
| SWT.WRAP | SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text, item, 5);
// text.setText(settingString);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setFocus() {
}

Your saveState() implementation should store the data you need in order to maintain the state.
See this short tutorial for code example.

Related

How to save selected check box in RCP application?

I am beginner of RCP framework.I have used one Editor in eclipse RCP3 application name like "Food editor". In this one of Editor I have made one SWT table with SWT.Check Table item.
I have facing problem regarding check box selection.
Current scenario of this editor is, when Food editor open then I select check box then I open new Editor name like Employee_Editor. Before Employee_Editor open, I closed Food editor with selected check box. Then again I open Food editor then previous one "Selected" check box display as "Unselected" why this happen?
I tried to get solution of this problem I search on internet I found solution using database "selected check box" save as datatype boolean.
But I do not want to do this because when many data comes many time SQL query fire.
So, I tried via defining one method "saveSelectedCheckBox" in createPartControl, which is save selected checkbox table item into "selectedTableItemList".
but in also I got problem when I close food editor then again I open it again I got problem with "selectedTableItemList" with null value.
I have share this code given below.
public class FoodDetailsEditor extends EditorPart {
public static final String ID = "rcp_demo.Editor.FoodDetailsEditor"; //$NON-NLS-1$Food_Details
public static final String BID = "Food_Details";
private static final String STORE_SELECTION = "rcp_demo.Editor.FoodDetailsEditor";
private Table table;
ArrayList<Integer> selectedTableItemList= null;
#Override
public void createPartControl(Composite parent) {
ScrolledComposite scrolledComposite_2 = new ScrolledComposite(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
scrolledComposite_2.setExpandHorizontal(true);
scrolledComposite_2.setExpandVertical(true);
Composite composite = new Composite(scrolledComposite_2, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION|SWT.CHECK);
GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
gd_table.heightHint = 156;
gd_table.widthHint = 565;
table.setLayoutData(gd_table);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tblclmnCheckbox = new TableColumn(table, SWT.NONE);
tblclmnCheckbox.setWidth(100);
tblclmnCheckbox.setText("Checkbox");
TableColumn tblclmnTiming = new TableColumn(table, SWT.NONE);
tblclmnTiming.setWidth(100);
tblclmnTiming.setText("Timing");
TableColumn tblclmnMonday = new TableColumn(table, SWT.NONE);
tblclmnMonday.setWidth(100);
tblclmnMonday.setText("Monday");
TableColumn tblclmnTuesday = new TableColumn(table, SWT.NONE);
tblclmnTuesday.setWidth(100);
tblclmnTuesday.setText("Tuesday");
TableColumn tblclmnWednesday = new TableColumn(table, SWT.NONE);
tblclmnWednesday.setWidth(100);
tblclmnWednesday.setText("Wednesday");
TableColumn tblclmnThursday = new TableColumn(table, SWT.NONE);
tblclmnThursday.setWidth(100);
tblclmnThursday.setText("Thursday");
TableColumn tblclmnFriday = new TableColumn(table, SWT.NONE);
tblclmnFriday.setWidth(100);
tblclmnFriday.setText("Friday");
TableColumn tblclmnSaturday = new TableColumn(table, SWT.NONE);
tblclmnSaturday.setWidth(100);
tblclmnSaturday.setText("Saturday");
scrolledComposite_2.setContent(composite);
scrolledComposite_2.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
TableItem item1 = new TableItem(table, SWT.NONE);
item1.setText(new String[]{"","10:00 to 10:30","Food1","Food2","Food3","Food4","Food5"});
TableItem item2 = new TableItem(table, SWT.NONE);
item2.setText(new String[]{"","11:00 to 11:30","Food1","Food2","Food3","Food4","Food5"});
TableItem item3 = new TableItem(table, SWT.NONE);
item3.setText(new String[]{"","12:00 to 12:30","Food1","Food2","Food3","Food4","Food5"});
TableItem item4 = new TableItem(table, SWT.NONE);
item4.setText(new String[]{"","13:00 to 13:30","Food1","Food2","Food3","Food4","Food5"});
table.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(SelectionEvent event)
{
if( event.detail == SWT.CHECK )
{
if( table.indexOf( ( TableItem )event.item ) == table.getSelectionIndex() )
{
TableItem ti = ( TableItem )event.item;
ti.setChecked( !ti.getChecked() );
System.out.println("event.index:-"+event.item);
}
}
saveSelectedCheckBox(table);
}
private void saveSelectedCheckBox(Table table) {
// TODO Auto-generated method stub
TableItem[] items = table.getItems();
selectedTableItemList=new ArrayList<Integer>();//Creating arraylist
for (int ro = 0; ro < table.getItemCount();ro++)
{ if(items[ro].getChecked()== true)
{
System.out.println("items[ro]:=="+items[ro]);
selectedTableItemList.add(ro);
}
}
for(int row = 0; row < selectedTableItemList.size();row++)
{
System.out.println("selectedTableItemList:--"+selectedTableItemList);
}
}
});
}
#Override
public void setFocus() {
// Set the focus
}
#Override
public void doSave(IProgressMonitor monitor) {
// Do the Save operation
}
#Override
public void doSaveAs() {
// Do the Save As operation
}
#Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
System.out.println("init called");
System.out.println("selectedTableItemList:--"+selectedTableItemList);
// Initialize the editor part
if (!(input instanceof FoodDetailsEditorInput)) {
throw new PartInitException("Invalid Input: Must be " + FoodDetailsEditorInput.class.getName());
}
setSite(site);
setInput(input);
}
#Override
public boolean isDirty()
{
return false;
}
#Override
public boolean isSaveAsAllowed() {
System.out.println("isSaveAsAllowed called");
return true;
}
}
I want when Food editor open then I select check box then I open new Editor name like Employee_Editor. Then again I open Food editor "Selected" check box as display as a "Selected". How to do this possible? Please help me.
My system configuration:
Windows 64Bit OS.
Eclipse Kepler 32 bit.
jdk 1.8
When you close an editor you lose it's state, and createPartControl() is performed again during open the editor. So you get your table in it's initial state. You should perform TableItem.setChecked() after you create your table and set values to the values of the previous user's choice. The best way to do it - turn the data in your table rows into objects and use TableViewer to create the table.
private TableViewer viewer;
private List<WeeklyMenu> menu = Menu.MENU.getWeeklyMenu();
public void createPartControl(Composite parent) {
Table table = createTable(parent);
viewer.setInput(menu);
for (TableItem item : table.getItems()) {
WeeklyMenu weeklyMenu = (WeeklyMenu)item.getData();
item.setChecked(weeklyMenu.isChecked());
}
viewer.refresh();
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if( e.detail == SWT.CHECK )
{
TableItem item = (TableItem)e.item;
WeeklyMenu weeklyMenu = (WeeklyMenu)item.getData();
weeklyMenu.setChecked(item.getChecked());
}
}
});
}
private Table createTable(Composite parent) {
viewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
viewer.setContentProvider(new IStructuredContentProvider() {
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public Object[] getElements(Object inputElement) {
return menu.toArray();
}
});
createColumns(table);
return table;
}
private void createColumns(Table table) {
TableLayout layout = new TableLayout();
layout.addColumnData(new ColumnWeightData(10, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
layout.addColumnData(new ColumnWeightData(20, true));
table.setLayout(layout);
TableViewerColumn column = createTableViewerColumn("Checkbox");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return "";
}
});
column = createTableViewerColumn("Timing");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getTiming();
}
});
column = createTableViewerColumn("Monday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getMonFood();
}
});
column = createTableViewerColumn("Tuesday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getTueFood();
}
});
column = createTableViewerColumn("Wednesday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getWedFood();
}
});
column = createTableViewerColumn("Thursday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getThuFood();
}
});
column = createTableViewerColumn("Friday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getFriFood();
}
});
column = createTableViewerColumn("Saturday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getSatFood();
}
});
column = createTableViewerColumn("Sunday");
column.setLabelProvider(new ColumnLabelProvider(){
#Override
public String getText(Object element) {
return ((WeeklyMenu)element).getSunFood();
}
});
}
private TableViewerColumn createTableViewerColumn(String name) {
TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.CENTER);
TableColumn column = viewerColumn.getColumn();
column.setText(name);
column.setMoveable(true);
return viewerColumn;
}
Class WeeklyMenu:
public class WeeklyMenu {
private boolean isChecked;
private String timing;
private String monFood;
private String tueFood;
private String wedFood;
private String thuFood;
private String friFood;
private String satFood;
private String sunFood;
public WeeklyMenu(boolean isChecked, String timing, String monFood, String tueFood, String wedFood, String thuFood, String friFood,
String sutFood, String sunFood) {
super();
this.isChecked = isChecked;
this.timing = timing;
this.monFood = monFood;
this.tueFood = tueFood;
this.wedFood = wedFood;
this.thuFood = thuFood;
this.friFood = friFood;
this.satFood = sutFood;
this.sunFood = sunFood;
}
public String getTiming() {
return timing;
}
public void setTiming(String timing) {
this.timing = timing;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getMonFood() {
return monFood;
}
public void setMonFood(String monFood) {
this.monFood = monFood;
}
public String getTueFood() {
return tueFood;
}
public void setTueFood(String tueFood) {
this.tueFood = tueFood;
}
public String getWedFood() {
return wedFood;
}
public void setWedFood(String wedFood) {
this.wedFood = wedFood;
}
public String getThuFood() {
return thuFood;
}
public void setThuFood(String thuFood) {
this.thuFood = thuFood;
}
public String getFriFood() {
return friFood;
}
public void setFriFood(String friFood) {
this.friFood = friFood;
}
public String getSatFood() {
return satFood;
}
public void setSatFood(String sutFood) {
this.satFood = sutFood;
}
public String getSunFood() {
return sunFood;
}
public void setSunFood(String sunFood) {
this.sunFood = sunFood;
}
}
And class Menu:
public class Menu {
public final static Menu MENU = new Menu();
private List<WeeklyMenu> weeklyMenu = new ArrayList<WeeklyMenu>();
private Menu(){
weeklyMenu.add(new WeeklyMenu(false, "10:00 to 10:30", "Food1", "Food2", "Food3", "Food4", "Food5", "Food6", "Food7"));
weeklyMenu.add(new WeeklyMenu(false, "10:30 to 11:00", "Food1", "Food2", "Food3", "Food4", "Food5", "Food6", "Food7"));
weeklyMenu.add(new WeeklyMenu(false, "11:00 to 11:30", "Food1", "Food2", "Food3", "Food4", "Food5", "Food6", "Food7"));
weeklyMenu.add(new WeeklyMenu(false, "11:30 to 12:00", "Food1", "Food2", "Food3", "Food4", "Food5", "Food6", "Food7"));
}
public List<WeeklyMenu> getWeeklyMenu() {
return weeklyMenu;
}
}
Add this classes to your project and replace your createPartControl() with the cited code snippet.
table.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(SelectionEvent event)
{
if( event.detail == SWT.CHECK )
{
if( table.indexOf( ( TableItem )event.item ) == table.getSelectionIndex() )
{
TableItem ti = ( TableItem )event.item;
ti.setChecked( !ti.getChecked() );
}
saveSelectedCheckBox(table);
}
}
private void saveSelectedCheckBox(Table table)
{
for (int ro = 0; ro < table.getItemCount();ro++)//#32
{ if(items[ro].getChecked()== true)//#32
{//#32
System.out.println("items[ro]:=="+items[ro]);//#32
selectedTableItemList.add(ro);//#32
}//#32
} //#32
for(int row = 0; row < selectedTableItemList.size();row++)//#32
{//#32
//*For FileSaving try
FileDialog dialog = new FileDialog(table.getShell(), SWT.SAVE);
TableItem[] items =table.getItems();
dialog.setText("Save");
String absolutePath = dialog.open();
if (absolutePath == null)
return;
File fl = new File(dialog.getFilterPath() + File.separator + dialog.getFileName());
FileWriter flwr;
int cls = table.getColumnCount();
try {
flwr = new FileWriter(fl);
for (int i = 0; i < items.length; i++) {
for (int j = 0; j <= cls; j++) {
flwr.write(items[i].getText(j) + "\t");
}
flwr.write("\n");
}
flwr.flush();
flwr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});

Saving Data Stored In viewpart in RCP application

I am using saveState method of viewPart to save my view state.Below is my code for saving data in my viewPart.
package view;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
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.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import tutogef.model.Connection;
import tutogef.model.Node;
import tutogef.model.Service;
import tutogef.xml.ThreatTypeXMLToObject;
public class Theartview extends ViewPart implements Serializable {
private static final long serialVersionUID = -3033215443267698138L;
public static String ID = "TutoGEF.theartview_id";
public static String ID1 = "TutoGEF.theartview_id1";
private Table table;
private String Theart_Name;
private String Category_Name;
private String Status_Name;
private String Priority_Name;
private String Descrption_Name;
private String Justification_Name;
private static Node sourceNode;
private static Node targetNode;
private static String connectionType;
private String shortDescription;
private String category;
private String description;
private ThreatTypeXMLToObject threattypexmltoobject;
private Connection conn;
private Text text_1, text_2, text_3, text_4;
private ArrayList<String> list1 = new ArrayList<>();
private HashMap<Integer, String> list2 = new HashMap<>();
// HashMap<Integer, String> list3 = new HashMap<>();
private static Integer a = 0;
private IMemento memento;
// String Key = "Key";
// String Key1 = "Key1";
// String Key2 = "Key2";
// String Key3 = "Key3";
// String Key4 = "Key4";
// String Key5 = "Key5";
// String Key6 = "Key6";
String[] keyValues = { "KeyValue1", "KeyValue2", "KeyValue3", "KeyValue4",
"KeyValue5", "KeyValue6" };
#SuppressWarnings("static-access")
public void getDataOfConnection(Node sourceNode, Node targetNode,
String connectionType1) {
this.sourceNode = sourceNode;
this.targetNode = targetNode;
this.connectionType = connectionType1;
}
public Theartview() {
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(10, false));
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 10, 1));
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Theart Name", "Category", "Satus", "Priority",
"Description", "Justification" };
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setWidth(150);
column.setText(titles[i]);
}
if (memento != null) {
System.out.println("Entering Restore State");
restoreState(memento);
}
memento = null;
}
void restoreState(IMemento memento) {
System.out.println("Restore State Entered");
IMemento[] mems = memento.getChildren(ID1);
System.out.println(mems);
for (int q = 0; q < mems.length; q+=3) {
System.out.println("Enter: -----------------------------");
IMemento mem = mems[q];
System.out.println(mems.length);
System.out.println(q);
System.out.println(mem);
TableItem item = new TableItem(table, SWT.NONE);
// for Theart_Name
TableEditor editor = new TableEditor(table);
Text text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 0);
text.setText(mem.getString(keyValues[q]));
Theart_Name = text.getText().toString().trim();
// For Category_Name
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 1);
text.setText(mem.getString(keyValues[q + 1]));
Category_Name = text.getText().toString().trim();
// For Status_Name
editor = new TableEditor(table);
final Combo Status_Combo = new Combo(table, SWT.READ_ONLY);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
Status_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
});
// For Priority_Name
editor = new TableEditor(table);
final Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
priority_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
});
// For Descrption_Name
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 4);
text.setText(mem.getString(keyValues[q + 2]));
Descrption_Name = text.getText().toString().trim();
// For justification
editor = new TableEditor(table);
text = new Text(table, SWT.MULTI | SWT.BORDER | SWT.WRAP
| SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text, item, 5);
Justification_Name = text.getText().toString().trim();
}
}
#SuppressWarnings("static-access")
public void fillTableRoWData() {
if (Connection.Number_Of_Connection != 0) {
// item = new TableItem(table, SWT.NONE);
if (Service.class.isInstance(sourceNode)) {
String id = "S1";
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(), null);
category = "Spoofing";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(), null);
fillRows(shortDescription, category, description);
}
if (Service.class.isInstance(sourceNode)
&& (connectionType == Connection.CONNECTION_DESIGN)) {
String id = "T1";
System.out.println(conn.getConnectionDesign());
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
category = "Tampering";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
fillRows(shortDescription, category, description);
}
}
System.out.println("Hash Map" + list2);
System.out.println("List : []" + list1);
}
#Override
public void setFocus() {
}
private void fillRows(String shortdesc, String categ, String descp) {
TableItem item = new TableItem(table, SWT.NONE);
// for Threat_Name
TableEditor editor = new TableEditor(table);
text_1 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_1, item, 0);
text_1.setText(shortdesc);
text_1.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent e) {
System.out.println("Modify Text");
Text text = (Text) e.widget;
System.out.println(text.getText());
}
});
Theart_Name = text_1.getText().toString().trim();
list1.add(Theart_Name);
list2.put(a, Theart_Name);
// For Category_Name
editor = new TableEditor(table);
text_2 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_2, item, 1);
text_2.setText(categ);
Category_Name = text_2.getText().toString().trim();
list1.add(Category_Name);
list2.put(++a, Category_Name);
// For Status_Name
editor = new TableEditor(table);
final Combo Status_Combo = new Combo(table, SWT.READ_ONLY);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
Status_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
list1.add(Status_Name);
list2.put(++a, Status_Name);
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
});
// For Priority_Name
editor = new TableEditor(table);
final Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
priority_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
list1.add(Priority_Name);
list2.put(++a, Priority_Name);
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
});
// For Descrption_Name
editor = new TableEditor(table);
text_3 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_3, item, 4);
text_3.setText(descp);
Descrption_Name = text_3.getText().toString().trim();
list1.add(Descrption_Name);
list2.put(++a, Descrption_Name);
// For justification
editor = new TableEditor(table);
text_4 = new Text(table, SWT.MULTI | SWT.BORDER | SWT.WRAP
| SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text_4, item, 5);
Justification_Name = text_4.getText().toString().trim();
list1.add(Justification_Name);
list2.put(++a, Justification_Name);
}
#Override
public void saveState(IMemento memento) {
super.saveState(memento);
System.out.println("Save State Called");
IMemento mem = memento.createChild(ID1);
for (int i = 0; i < 6; i++) {
mem.putString(keyValues[i], list2.get(i));
System.out.println("Hash Map Values: [" + i + "] " + list2.get(i));
System.out.println(mem);
}
}
#Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
this.memento = memento;
System.out.println("Intialize the view");
}
}
Following problem occurs
1) When memento is initialized for the first time the code works properly. But when I open up my viewPart again without changing any data the error occurs.
2) I have stored all my values in hashmap. When I restore data I only get the first 3 values rest of the values does not appear. If I use numbers than all the data comes properly. Any solutions for that?
3) In my fillTableRoWData() method when the two if conditions are executed all my listeners stand at the second conditions only. How to move the listeners between two if conditions.
Use the org.eclipse.ui.elementFactories extension point and implement the createElement method of the IElementFactory interface which takes an IMemento object.
If you want to make the view Saveable then make the viewpart implement ISaveablePart

e4 load table in Mpart using parthandler

i am a beginner in E4 and at all in JAVA.
i created a partHandler and i want to display table which is created in other class in this part. table is cteated in TreeTableCreation class. it would be nice if you can help.
now it creates a Tab, but no table inside, and throws Nullpointer exception. tahnk you.
public class DynamicPartHandlerCode {
#Execute
public void execute(EModelService modelService, MApplication application, final IEclipseContext context,
#Named(IServiceConstants.ACTIVE_SHELL) final Shell shell) {
EPartService partService = context.get(EPartService.class);
// create new part
MPart mPart = modelService.createModelElement(MPart.class);
String id = "org.testeditor.ui.uidashboard.partdescriptor.0";
mPart = partService.findPart(id);
if (mPart == null) {
mPart = partService.createPart(id);
}
List<MPartStack> stacks = modelService.findElements(application, null, MPartStack.class, null);
stacks.get(2).getChildren().add(mPart);
((TreeTableCreation) mPart.getObject()).createTable();
partService.showPart(mPart, PartState.ACTIVATE);
}
}
here class to create table
public class TreeTableCreation {
// Injected services
#Inject
#Named(IServiceConstants.ACTIVE_SHELL)
Shell shell;
#Inject
MPart mPart;
public void createTable() {
// public static void main(String[] args) {
// Shell shell;
Display display = new Display();
// final Shell shell = new Shell(display);
// shell = new Shell(Display.getCurrent());
// shell.setSize(500, 500);
shell.setLayout(new FillLayout());
final Tree tree = new Tree(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
final TreeViewer v = new TreeViewer(tree);
// Header der
// Tabelle*********************************************************************
String[] titles = { "Datum ", "Testname", "Erfolgreich", "Durchgefallen", "Dauer", "Läufe" };
for (int i = 0; i < titles.length; i++) {
TreeColumn column = new TreeColumn(tree, SWT.CENTER);
column.setText(titles[i]);
column.setWidth(150);
}
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setInput(TestResultTest.getData());
// // selecting cells getting
// // items******************************************************
tree.addListener(SWT.MouseDoubleClick, new Listener() {
final int columnCount = 6;
public void handleEvent(Event event) {
Point pt = new Point(event.x, event.y);
TreeItem item = tree.getItem(pt);
int index = tree.indexOf(item);
System.out.println("Item Index-" + index);
if (item == null)
return;
for (int i = 0; i < columnCount; i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
TreeTableCreation2 anothershell = new TreeTableCreation2();
DrawMultipleLine grafshell = new DrawMultipleLine();
anothershell.open();
System.out.println("Läufe gewählt");
grafshell.open();
System.out.println("Dauer gewählt");
}
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
You can't just convert a standalone SWT program like this. You need to read a tutorial on writing e4 programs such as this one
You must not create a new Display, e4 already has one.
You must not mess around with the current Shell, e4 is in charge of that and has many other objects already in the Shell.
Do not call shell.pack, shell.open or use a display dispatch loop.
Do not dispose of the display.
Do not do ((TreeTableCreation) mPart.getObject()).createTable();. Use the #PostConstruct method of the part.
So something like:
public class TreeTableCreation {
#PostConstruct
public void createTable(Composite parent) {
final Tree tree = new Tree(parent, SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
final TreeViewer v = new TreeViewer(tree);
// Header der
// Tabelle*********************************************************************
String[] titles = { "Datum ", "Testname", "Erfolgreich", "Durchgefallen", "Dauer", "Läufe" };
for (int i = 0; i < titles.length; i++) {
TreeColumn column = new TreeColumn(tree, SWT.CENTER);
column.setText(titles[i]);
column.setWidth(150);
}
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setInput(TestResultTest.getData());
// // selecting cells getting
// // items******************************************************
tree.addListener(SWT.MouseDoubleClick, new Listener() {
final int columnCount = 6;
public void handleEvent(Event event) {
Point pt = new Point(event.x, event.y);
TreeItem item = tree.getItem(pt);
int index = tree.indexOf(item);
System.out.println("Item Index-" + index);
if (item == null)
return;
for (int i = 0; i < columnCount; i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
TreeTableCreation2 anothershell = new TreeTableCreation2();
DrawMultipleLine grafshell = new DrawMultipleLine();
anothershell.open();
System.out.println("Läufe gewählt");
grafshell.open();
System.out.println("Dauer gewählt");
}
}
}
});
}

How to sort a table column by clicking on the header in SWT? [duplicate]

In swt table- sorting works for Strings how to do sorting for Integer, Double and Date values. And this only works for String ascending. Can anyone suggest a better way to do it.
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "1", "v", "1.1", "20/03/2013" });
item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "10", "z", "1.5", "20/04/2013" });
item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "3", "a", "1.3", "30/01/2013" });
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableItem[] items = table.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
TableColumn column = (TableColumn) e.widget;
int index = column == tblclmnNumber ? 0 : 1;
for (int i = 1; i < items.length; i++) {
String value1 = items[i].getText(index);
for (int j = 0; j < i; j++) {
String value2 = items[j].getText(index);
if (collator.compare(value1, value2) < 0) {
String[] values = { items[i].getText(0),
items[i].getText(1), items[i].getText(2),
items[i].getText(3) };
items[i].dispose();
TableItem item = new TableItem(table, SWT.NONE, j);
item.setText(values);
items = table.getItems();
break;
}
}
}
table.setSortColumn(column);
}
};
tblclmnNumber.addListener(SWT.Selection, sortListener);
tblclmnName.addListener(SWT.Selection, sortListener);
tblclmnDeci.addListener(SWT.Selection, sortListener);
tblclmnDate.addListener(SWT.Selection, sortListener);
table.setSortColumn(tblclmnNumber);
table.setSortDirection(SWT.UP);
I've modified the SWT snippet with sorting to show how is possible to sort columns with with different data types..
/*
* Table example snippet: sort a table by column
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*
* #since 3.2
*/
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
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;
public class SortTable {
private TableRow rows[] = new TableRow[] {
new TableRow(1, "aaa", new Date(1363784269000L)),
new TableRow(2, "abc", new Date(1367784269000L)),
new TableRow(3, "efc", new Date(1363584269000L)),
new TableRow(4, "ccc", new Date(1363734269000L)),
};
private Table table;
private TableColumn intColumn;
private TableColumn strColumn;
private TableColumn dateColumn;
public SortTable() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
table = new Table(shell, SWT.BORDER);
table.setHeaderVisible(true);
intColumn = new TableColumn(table, SWT.NONE);
intColumn.setText("int");
intColumn.setWidth(50);
strColumn = new TableColumn(table, SWT.NONE);
strColumn.setText("string");
strColumn.setWidth(50);
dateColumn = new TableColumn(table, SWT.NONE);
dateColumn.setText("date");
dateColumn.setWidth(100);
updateTable();
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableColumn column = (TableColumn) e.widget;
if (column == intColumn) Arrays.sort(rows, BY_VAL);
if (column == strColumn) Arrays.sort(rows, BY_STR);
if (column == dateColumn) Arrays.sort(rows, BY_DATE);
table.setSortColumn(column);
updateTable();
}
};
intColumn.addListener(SWT.Selection, sortListener);
strColumn.addListener(SWT.Selection, sortListener);
dateColumn.addListener(SWT.Selection, sortListener);
shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private void updateTable() {
table.removeAll();
for (TableRow row : rows) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(row.asString());
}
}
public final Comparator<TableRow> BY_VAL = new Comparator<TableRow>() {
#Override
public int compare(TableRow o1, TableRow o2) {
if (o1.val < o2.val) return -1;
if (o1.val > o2.val) return 1;
return 0;
}
};
public final Comparator<TableRow> BY_STR = new Comparator<TableRow>() {
#Override
public int compare(TableRow o1, TableRow o2) {
return o1.str.compareTo(o2.str);
}
};
public final Comparator<TableRow> BY_DATE = new Comparator<TableRow>() {
#Override
public int compare(TableRow o1, TableRow o2) {
return o1.date.compareTo(o2.date);
}
};
private class TableRow {
private int val;
private String str;
private Date date;
private SimpleDateFormat format = new SimpleDateFormat();
public TableRow(int val, String str, Date date) {
this.val = val;
this.str = str;
this.date = date;
}
public String[] asString() {
return new String[] {Integer.toString(val), str, format.format(date)};
}
}
public static void main(String[] args) {
new SortTable();
}
}
Summarize it's totally up to programmer how will be columns in table sorted, because table just always wants array of String for a row whatever they mean..
You can throw a comparator for the column in as data to the column, and then use it to sort. This keeps the sorting logic closer to the definition of the column itself.
intColumn = new TableColumn(table, SWT.NONE);
intColumn.setText("int");
intColumn.setWidth(50);
intColumn.setData(new Comparator<TableItem>() {
#Override
public int compare(TableItem t1, TableItem t2) {
int i1 = Integer.parseInt(t1.getText(0));
int i2 = Integer.parseInt(t2.getText(0));
if (i1.val < i2.val) return -1;
if (i1.val > i2.val) return 1;
return 0;
}
};
strColumn = new TableColumn(table, SWT.NONE);
strColumn.setText("string");
strColumn.setWidth(50);
strColumn.setData(new Comparator<TableItem>() {
#Override
public int compare(TableItem t1, TableItem t2) {
return t1.getText(1).compareTo(t2.getText(1));
}
};
dateColumn = new TableColumn(table, SWT.NONE);
dateColumn.setText("date");
dateColumn.setWidth(100);
dateColumn.setData(new Comparator<TableItem>() {
#Override
public int compare(TableItem t1, TableItem t2) {
return Date.parse(t1.getText(2)).compareTo(Date.parse(t2.getText(2)));
}
};
Listener sortListener = e -> {
TableColumn sortColumn = table.getSortColumn();
TableColumn selectedColumn = (TableColumn) e.widget;
int dir = table.getSortDirection();
if (sortColumn == selectedColumn) {
dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
} else {
table.setSortColumn(selectedColumn);
dir = SWT.UP;
}
TableItem[] items = table.getItems();
final Comparator<TableItem> comparator = (Comparator<TableItem>) selectedColumn.getData();
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < i; j++) {
if ((comparator.compare(items[i], items[j]) < 0 && dir == SWT.UP) || (comparator.compare(items[i], items[j]) > 0 && dir == SWT.DOWN)) {
String[] oldItem = new String[table.getColumnCount()];
for (int h = 0; h < table.getColumnCount(); h++) {
item[h] = items[i].getText(h);
}
items[i].dispose();
TableItem newItem = new TableItem(table, SWT.NONE, j);
newItem.setText(oldItem);
items = table.getItems();
break;
}
}
}
table.setSortDirection(dir);
};

Synchronize Selections in two Tables with the same color

I have two SWT Tables in a Shell.
When the user clicks on a row in one table, I want the corresponding row in the next Table to be selected too.
However, in the current setup (I'm demonstrating with a Snippet I found online) when one row is clicked, the corresponding row is highlighted too but it's in grey. I'd like the selection to be the same purple everywhere.
The Source Code:
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class Snippet234 {
public static void main (String [] args) {
int rowCount = 40;
int columnCount = 15;
final Display display = new Display ();
Shell shell = new Shell (display);
shell.setLayout(new FillLayout());
Composite parent = new Composite(shell, SWT.BORDER);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = layout.marginHeight = layout.horizontalSpacing = 0;
parent.setLayout(layout);
final Table leftTable = new Table(parent, SWT.MULTI | SWT.FULL_SELECTION);
leftTable.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true));
leftTable.setHeaderVisible(true);
final Table rightTable = new Table(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
rightTable.setHeaderVisible(true);
GridData table2Data = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2);
rightTable.setLayoutData(table2Data);
// Create columns
TableColumn column1 = new TableColumn(leftTable, SWT.NONE);
column1.setText("Name");
column1.setWidth(150);
for (int i = 0; i < columnCount; i++) {
TableColumn column = new TableColumn(rightTable, SWT.NONE);
column.setText("Value "+i);
column.setWidth(200);
}
// Create rows
for (int i = 0; i < rowCount; i++) {
TableItem item = new TableItem(leftTable, SWT.NONE);
item.setText("item "+i);
item = new TableItem(rightTable, SWT.NONE);
for (int j = 0; j < columnCount; j++) {
item.setText(j, "Item "+i+" value # "+j);
}
}
// Make selection the same in both tables
leftTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
rightTable.setSelection(leftTable.getSelectionIndices());
}
});
rightTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
leftTable.setSelection(rightTable.getSelectionIndices());
}
});
// On Windows, the selection is gray if the table does not have focus.
// To make both tables appear in focus, draw the selection background here.
// This part only works on version 3.2 or later.
/*
Listener eraseListener = new Listener() {
public void handleEvent(Event event) {
event.detail &= ~SWT.HOT;
if((event.detail & SWT.SELECTED) != 0) {
GC gc = event.gc;
Rectangle rect = event.getBounds();
gc.setForeground(display.getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
gc.setBackground(display.getSystemColor(SWT.COLOR_LIST_SELECTION));
gc.fillRectangle(rect);
event.detail &= ~SWT.SELECTED;
}
}
};
leftTable.addListener(SWT.EraseItem, eraseListener);
rightTable.addListener(SWT.EraseItem, eraseListener);
*/
// Make vertical scrollbars scroll together
ScrollBar vBarLeft = leftTable.getVerticalBar();
vBarLeft.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
rightTable.setTopIndex(leftTable.getTopIndex());
}
});
ScrollBar vBarRight = rightTable.getVerticalBar();
vBarRight.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
leftTable.setTopIndex(rightTable.getTopIndex());
}
});
// Horizontal bar on second table takes up a little extra space.
// To keep vertical scroll bars in sink, force table1 to end above
// horizontal scrollbar
ScrollBar hBarRight = rightTable.getHorizontalBar();
Label spacer = new Label(parent, SWT.NONE);
GridData spacerData = new GridData();
spacerData.heightHint = hBarRight.getSize().y;
spacer.setVisible(false);
parent.setBackground(leftTable.getBackground());
shell.setSize(600, 400);
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
Ok, I threw something together for you. Don't mind the crappy way of handling the selection, that's not what I want to show. The important part is where I draw the background of the item, i.e. the MyLabelProviders paint() method:
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final TableViewer first = new TableViewer(shell);
addColumn(first);
first.setContentProvider(ArrayContentProvider.getInstance());
final List<MyObject> firstInput = getInput();
first.setInput(firstInput);
first.setLabelProvider(new MyLabelProvider());
final TableViewer second = new TableViewer(shell);
addColumn(second);
second.setContentProvider(ArrayContentProvider.getInstance());
final List<MyObject> secondInput = getInput();
second.setInput(secondInput);
second.setLabelProvider(new MyLabelProvider());
first.addSelectionChangedListener(new ISelectionChangedListener()
{
#Override
public void selectionChanged(SelectionChangedEvent e)
{
int index = first.getTable().getSelectionIndex();
second.getTable().setSelection(index);
setSelection(firstInput, index);
setSelection(secondInput, index);
}
});
second.addSelectionChangedListener(new ISelectionChangedListener()
{
#Override
public void selectionChanged(SelectionChangedEvent e)
{
int index = second.getTable().getSelectionIndex();
first.getTable().setSelection(index);
setSelection(firstInput, index);
setSelection(secondInput, index);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static void setSelection(List<MyObject> input, int index)
{
for(MyObject obj : input)
{
obj.setSelected(false);
}
input.get(index).setSelected(true);
}
private static List<MyObject> getInput()
{
List<MyObject> result = new ArrayList<MyObject>();
result.add(new MyObject("First"));
result.add(new MyObject("Second"));
result.add(new MyObject("Third"));
return result;
}
private static void addColumn(TableViewer viewer)
{
TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
col.getColumn().setWidth(200);
col.getColumn().setText("Name:");
col.setLabelProvider(new ColumnLabelProvider()
{
#Override
public String getText(Object element)
{
MyObject value = (MyObject) element;
return value.getName();
}
});
}
private static class MyObject
{
private String name;
private boolean isSelected;
public MyObject(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSelected()
{
return isSelected;
}
public void setSelected(boolean isSelected)
{
this.isSelected = isSelected;
}
#Override
public String toString()
{
return name;
}
}
private static class MyLabelProvider extends StyledCellLabelProvider
{
#Override
protected void paint(Event event, Object element)
{
int width = 1000;
int x = event.x - 2;
int y = event.y;
int height = event.height;
GC gc = event.gc;
MyObject object = (MyObject) element;
Color oldBackground = gc.getBackground();
Color color = object.isSelected ? Display.getCurrent().getSystemColor(SWT.COLOR_LIST_SELECTION) : Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND);
gc.setBackground(color);
gc.fillRectangle(x, y, width, height);
gc.setBackground(oldBackground);
super.paint(event, element);
}
}
Here are two screenshots after selecting the first and then the third row (doesn't matter which TableViewer):

Categories