jFace CheckboxTableViewer and content provider - java

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.

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

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

TableViewer.refresh not working

The two events that I add to the table viewer are not appearing on the screen.
Here is my code to create the table viewer, table, and one column
TableViewer tableViewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
fd_btnNewButton.left = new FormAttachment(table, 6);
FormData fd_table = new FormData();
fd_table.top = new FormAttachment(eventLabel, 6);
fd_table.left = new FormAttachment(0, 10);
fd_table.right = new FormAttachment(100, -100);
fd_table.bottom = new FormAttachment(eventLabel, 387, SWT.BOTTOM);
table.setLayoutData(fd_table);
TableColumn tableColumn = new TableColumn(table,SWT.LEFT);
String[] column_names = new String[]{"Events"};
tableColumn.setText(column_names[0]);
tableViewer.setColumnProperties(column_names);
tableViewer.setLabelProvider(new ContinuousIntegrationLabelProvider());
tableViewer.setContentProvider(new ContinuousIntegrationContentProvider());
The table is being created successfully.. Next, I am setting the inputs and then refreshing the table...
events.add("Build"); //events is an ArrayList<String>
events.add("JUnit Tests");
tableViewer.setInput(events);
tableViewer.refresh();
And here are my provider methods:
/**
* label provider for the table
*/
public class ContinuousIntegrationLabelProvider extends LabelProvider implements ITableLabelProvider {
/**
* image for the column
*/
public Image getColumnImage(Object element, int index){
switch(index){
case 0:
if(model.getJenkinsJob() == null){
return Images.getImage(Images.WARNING);
}
else{
return null;
}
default:
return null;
}
}
/**
* returns the correct value for each column
*/
public String getColumnText(Object element, int index){
switch(index){
case 0:
return (String) element;
default:
return "";
}
}
And here is my content provider:
/**
* content provider for the table
*/
public class ContinuousIntegrationContentProvider implements IStructuredContentProvider {
#SuppressWarnings("unchecked")
public Object[] getElements(Object inputElement) {
ArrayList<String> data = (ArrayList<String>) inputElement;
return data.toArray();
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
I just needed to set the width on the table column and then everything would show up.
Here is the portion of the code that I changed:
TableColumn tableColumn = new TableColumn(table, SWT.LEFT);
String[] column_names = new String[]{"Events"};
tableColumn.setText(column_names[0]);
tableColumn.setWidth(352);

Last column gets oversized in jface

I'm quite new with Jface, and right now I'm facing a problem with the last column in a table. Take a look at the next screenshot:
As you can see, the last column gets oversized when the application is initiated, and I can't fix that, no matter what! Below you can see the View code:
package de.vogella.jface.tableviewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import de.vogella.jface.tableviewer.model.CenterImageLabelProvider;
import de.vogella.jface.tableviewer.model.ModelProvider;
import de.vogella.jface.tableviewer.model.Person;
public class View extends ViewPart {
public static final String ID = "de.vogella.jface.tableviewer.view";
private TableViewer viewer;
// static fields to hold the images
private static final Image CHECKED = Activator.getImageDescriptor(
"icons/checked.gif").createImage();
private static final Image UNCHECKED = Activator.getImageDescriptor(
"icons/unchecked.gif").createImage();
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
Label searchLabel = new Label(parent, SWT.NONE);
searchLabel.setText("Search: ");
final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
| GridData.HORIZONTAL_ALIGN_FILL));
createViewer(parent);
}
private void createViewer(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
createColumns(parent, viewer);
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
viewer.setContentProvider(new ArrayContentProvider());
// get the content for the viewer, setInput will call getElements in the
// contentProvider
viewer.setInput(ModelProvider.INSTANCE.getPersons());
// make the selection available to other views
getSite().setSelectionProvider(viewer);
// set the sorter for the table
// define layout for the viewer
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
}
public TableViewer getViewer() {
return viewer;
}
// create the columns for the table
private void createColumns(final Composite parent, final TableViewer viewer) {
String[] titles = { "First name", "Last name", "Gender", "Married", "Age" };
int[] bounds = { 100, 100, 100, 100, 100 };
// first column is for the first name
TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getFirstName();
}
});
// second column is for the last name
col = createTableViewerColumn(titles[1], bounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getLastName();
}
});
// now the gender
col = createTableViewerColumn(titles[2], bounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getGender();
}
});
// now the status married
col = createTableViewerColumn(titles[3], bounds[3], 3);
col.setLabelProvider(new CenterImageLabelProvider() {
#Override
public Image getImage(Object element) {
if (((Person) element).isMarried()) {
return CHECKED;
}
else {
return UNCHECKED;
}
}
});
// now the age
col = createTableViewerColumn(titles[4], bounds[4], 4);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getAge().toString();
}
});
}
private TableViewerColumn createTableViewerColumn(String title,
int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
SWT.CENTER);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
public void setFocus() {
viewer.getControl().setFocus();
}
}
How can I fix this?
Your layout on the viewer:
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
says that you want the viewer to use all the available horizontal space, so the viewer has had to resize the last column to make this happen.
Use
gridData.grabExcessHorizontalSpace = false;
gridData.horizontalAlignment = GridData.BEGINNING;
to not grab the extra space.
Alternatively to fill the space available leave the GridData alone and use TableLayout and ColumnWeightData, something like:
TableLayout tableLayout = new TableLayout();
table.setLayout(tableLayout);
...
... don't call column.setWidth replace with:
tableLayout.addColumnData(new ColumnWeightData(nnn));
nnn is a number you choose for each column and is the 'weight' used to calculate the width of the column.

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