How to save selected check box in RCP application? - java

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

Related

SWT/JFace Tab with TableViewer not drawing viewer until a shell resize

On a new project I started use SWT/JFace for a desktop app. This is for a standalone application not an Eclipse RCP app. I've built out a few parts and I currently have a TabFolder that is not working properly.
When this component is created, it holds a TabFolder, that tabs will be added to. Each tab holds a TableViewer. It all seems to be working but I have an annoying issue that I can't seem to get right.
When the tab is added it opens and the tab content area is blank. Resizing the screen causes the tab's TableViewer to appear as expected filling the tab. I've tried setting focus, redraw, update, pack. Nothing seems to cause it to properly appear until resizing the shell. I also have this constant output of a warning that I'm not sure if its related.
(SWT:121939): Gtk-WARNING **: 17:13:42.617: Negative content width -2 (allocation 15, extents 8x9) while allocating gadget (node button, owner GtkButton)
Any ideas why I can't get it to properly display the table viewer when it displays the tab?
public class RegistryTabView extends Composite {
private static final int[] COLUMN_SIZES = { 15, 90, 55, 175, 125, 150, 75, 75, 75 };
private static final String[] COLUMN_TITLES = { " ", "Date", "#", "Payee", "Memo", "Category", "Credit", "Debit" };
private AccountService accountService;
private CategoryService categoryService;
private TabFolder tabFolder;
private Map<String, TabItem> tabs;
private TransactionService transactionService;
public RegistryTabView(Composite parent, AccountService accountService, CategoryService categoryService, TransactionService transactionService) {
super(parent, SWT.NONE);
this.accountService = accountService;
this.transactionService = transactionService;
this.categoryService = categoryService;
tabs = new HashMap<>();
setLayout(new FillLayout());
tabFolder = new TabFolder(this, SWT.BORDER);
tabFolder.setLayout(new FillLayout());
}
protected TableViewerColumn createColumn(TableViewer viewer, String label, int width)
{
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, width);
final TableColumn column = viewerColumn.getColumn();
column.setText(label);
column.setMoveable(false);
column.setResizable(true);
column.setWidth(width);
return viewerColumn;
}
public void openAccountRegistry(AccountEntity account) {
TabItem tab = tabs.get(account.getName());
if (tab != null) {
tabFolder.setSelection(tab);
} else {
tab = new TabItem(tabFolder, SWT.TOP);
tab.setText(account.getName());
tabs.put(account.getName(), tab);
final TableViewer viewer = new TableViewer(tabFolder);
viewer.setContentProvider(new RegistryContentProvider());
viewer.getTable().setHeaderVisible(true);
viewer.getTable().setLinesVisible(true);
// Status
int counter = 0;
TableViewerColumn column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
final StatusTypeEntity state = ((AccountTransactionEntity) element).getState();
return super.getText(state == null ? "" : state.getName());
}
});
// Date
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
final Long enteredDate = ((AccountTransactionEntity) element).getEnterDate();
if (enteredDate == null) {
return super.getText(format.format(new Date()));
}
return super.getText(format.format(new Date(enteredDate)));
}
});
// Check number
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return super.getText(((AccountTransactionEntity) element).getCheckNumber());
}
});
// Payee
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return super.getText(((AccountTransactionEntity) element).getPayee());
}
});
// Memo
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return super.getText(((AccountTransactionEntity) element).getMemo());
}
});
// Category
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return CategoryService.getCategoryName(((AccountTransactionEntity) element).getCategory());
}
});
// Credit
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
final AccountTransactionEntity entity = (AccountTransactionEntity) element;
final TransactionTypeEntity transactionType = entity.getType();
Double value = 0.0;
final NumberFormat formatter = NumberFormat.getCurrencyInstance();
if (transactionType != null && transactionType.getId() == 2) {
value = ((AccountTransactionEntity) element).getAmount();
}
return formatter.format(value);
}
});
// Debit
counter++;
column = createColumn(viewer, COLUMN_TITLES[counter], COLUMN_SIZES[counter]);
column.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
final AccountTransactionEntity entity = (AccountTransactionEntity) element;
final TransactionTypeEntity transactionType = entity.getType();
Double value = 0.0;
final NumberFormat formatter = NumberFormat.getCurrencyInstance();
if (transactionType != null && transactionType.getId() == 1) {
value = ((AccountTransactionEntity) element).getAmount();
}
return formatter.format(value);
}
});
final List<AccountTransactionEntity> transactions = transactionService.getTransactions(account.getId(), 0l,
150);
transactions.add(new AccountTransactionEntity());
viewer.setInput(transactions);
tab.setControl(viewer.getTable());
tabFolder.setSelection(tab);
viewer.getTable().forceFocus();
}
}
}

Save ViewPart on Exit

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.

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

jFace CheckboxTableViewer and content provider

i am new to jFace. I'm using the following TableViewer Class as an example:
public class AppPersonViewer extends TableViewer
{
public Table table;
public AppPersonViewer(Composite parent, int style)
{
super(parent, style);
table = getTable();
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
table.setLayoutData(gridData);
createColumns();
table.setHeaderVisible(true);
table.setLinesVisible(true);
setContentProvider(new AppContentProvider());
}
private void createColumns()
{
String[] titles = { "First Name", "Second Name", "Age", "Country", "Likes SO" };
int[] bounds = { 150, 150, 100, 150, 100 };
TableViewerColumn column = createTableViewerColumn(titles[0], bounds[0], 0);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getFirst();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[1], bounds[1], 1);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getSecond();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[2], bounds[2], 2);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ""+((Person)element).getAge();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[3], bounds[3], 3);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getCountry();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[4], bounds[4], 4);
column.setLabelProvider(new ColumnLabelProvider(){
public Image getImage(Object element) {
return ((Person)element).getImage();
}
public String getText(Object element) {
return null; // no string representation, we only want to display the image
}
});
}
private TableViewerColumn createTableViewerColumn(String header, int width, int idx)
{
TableViewerColumn column = new TableViewerColumn(this, SWT.LEFT, idx);
column.getColumn().setText(header);
column.getColumn().setWidth(width);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
return column;
}
}
The example works great. Now i want to display checkboxes in the first column of each table row. (In native SWT the flag SWT.CHECK does that work).
After some searching i found the class CheckboxTableViewer. So i changed the example to:
public class AppPersonViewer extends CheckboxTableViewer
{
public Table table;
public AppPersonViewer(Composite parent, int style)
{
super(parent, style);
table = getTable();
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
table.setLayoutData(gridData);
createColumns();
table.setHeaderVisible(true);
table.setLinesVisible(true);
setContentProvider(new AppContentProvider());
}
.
.
.
The checkboxes are displayed now, but i have no idea how to use the checkboxes in my content provider. Any idea?
The CheckboxTableViewer uses a separate ICheckStateProvider to set the check boxes.
Set with
viewer.setCheckStateProvider(checkStateProvider);
The provider has two methods isChecked and isGrayed.
The values passed to these methods are the objects from your content provider.
Alternatively CheckboxTableViewer has setChecked, setAllChecked, ... methods.

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