Getting the value of a cell in a swt table - java

I created a swt table that has 3 columns, the first is check column. I used this code:
table = new Table(container, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL|SWT.MULTI);
When I select one item, a text is created in the third colonm. the code is as below:
listener = new Listener() {
#Override public void handleEvent(Event event) {
if (event.detail == SWT.CHECK) {
final TableItem current = (TableItem) event.item;
if (current.getChecked()) {
final TableEditor editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
}
I want to get the value of the cell that matches the selected item with the third column but couldn't get it with a selectedItem.getText(2).
Any help please?

Try this code sample. It will print out the text in column 3 of the selected TableItem:
public static void main(String[] args)
{
Display display = Display.getDefault();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, true));
Table table = new Table(shell, SWT.CHECK | SWT.MULTI);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
for(int i = 0; i < 4; i++)
{
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText("Column " + i + " ");
column.pack();
}
for(int i = 0; i < 10; i++)
{
TableItem newItem = new TableItem(table, SWT.NONE);
newItem.setText(1, "ITEM " + i + " TEXT1");
newItem.setText(2, "ITEM " + i + " TEXT2");
newItem.setText(3, "ITEM " + i + " TEXT3");
}
table.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event event)
{
if(event.detail == SWT.CHECK)
{
TableItem current = (TableItem)event.item;
if(current.getChecked())
{
System.out.println(current.getText(2));
}
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
This is what it looks like:

Related

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

SWT Text Listener

I have a Text in SWT:
final Text textArea = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
textArea.setVisible(false);
textArea.setEditable(false);
textArea.setEnabled(false);
textArea.setText("Scheduler Info");
I have a listener. Once the listener is fired, I would like some data to overwrite again and again in the text area. Is there anyway I can retain the "Scheduler Info" Header in the text area. I do not want the first line to be overwritten. I want the rest of the area to be overwritten.
There are two ways you can do this:
Just use Text#setText(String) with your new String and prepend the original string.
Select everything after the original string and Text#insert(String) your new stuff.
Here is an example with both methods:
private static final String INITIAL_TEXT = "Scheduler Info";
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final Text text = new Text(shell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
text.setEditable(false);
text.setEnabled(false);
text.setText(INITIAL_TEXT);
Button replace = new Button(shell, SWT.PUSH);
replace.setText("Replace");
replace.addListener(SWT.Selection, new Listener()
{
private int counter = 1;
#Override
public void handleEvent(Event arg0)
{
String replace = INITIAL_TEXT;
for(int i = 0; i < counter; i++)
replace += "\nLine " + i;
text.setText(replace);
counter++;
}
});
Button insert = new Button(shell, SWT.PUSH);
insert.setText("Insert");
insert.addListener(SWT.Selection, new Listener()
{
private int counter = 1;
#Override
public void handleEvent(Event arg0)
{
text.setSelection(INITIAL_TEXT.length(), text.getText().length());
String newText = "";
for(int i = 0; i < counter; i++)
newText += "\nLine " + i;
text.insert(newText);
counter++;
}
});
shell.pack();
shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}

Programmatically scroll ExpandBar

In my code, org.eclipse.swt.widgets.ExpandBar contains multiple ExpandItems. The ExpandBar is setup to scroll. How do I programmetically scroll the ExpandBar? I looked for examples and API but no luck.
Alright, wrap your ExpandBar in a ScrolledComposite and let it handle scrolling.
The advantage of this is that ScrolledComposite has a method called .setOrigin(int, int) which you can use to scroll to a position.
Here is some example code:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("ExpandBar Example");
final ScrolledComposite scrolledComp = new ScrolledComposite(shell, SWT.V_SCROLL);
final ExpandBar bar = new ExpandBar(scrolledComp, SWT.NONE);
for (int i = 0; i < 3; i++)
{
Composite composite = new Composite(bar, SWT.NONE);
composite.setLayout(new GridLayout());
for (int j = 0; j < 10; j++)
new Label(composite, SWT.NONE).setText("Label " + i + " " + j);
ExpandItem item = new ExpandItem(bar, SWT.NONE, 0);
item.setText("Item " + i);
item.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item.setControl(composite);
}
bar.getItem(1).setExpanded(true);
bar.setSpacing(8);
/* Make sure to update the scrolled composite when we collapse/expand
* items */
Listener updateScrolledSize = new Listener()
{
#Override
public void handleEvent(Event arg0)
{
display.asyncExec(new Runnable()
{
#Override
public void run()
{
scrolledComp.setMinSize(bar.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
}
};
bar.addListener(SWT.Expand, updateScrolledSize);
bar.addListener(SWT.Collapse, updateScrolledSize);
scrolledComp.setContent(bar);
scrolledComp.setExpandHorizontal(true);
scrolledComp.setExpandVertical(true);
scrolledComp.setMinSize(bar.computeSize(SWT.DEFAULT, SWT.DEFAULT));
shell.setSize(400, 200);
shell.open();
/* Jump to the end */
scrolledComp.setOrigin(0, scrolledComp.getSize().y);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
Looks like this after running:
As you can see it's scrolled to the end.
Update
Ok, if you want to jump to the position of a specific item, do the following:
Add a Button to test the functionality. Inside the Listener, get the y position and scroll to it:
Button jumpTo = new Button(shell, SWT.PUSH);
jumpTo.setText("Jump to item");
jumpTo.addListener(SWT.Selection, new Listener()
{
private int counter = 0;
#Override
public void handleEvent(Event e)
{
int y = getYPosition(bar, counter);
/* Increment the counter */
counter = (counter + 1) % bar.getItemCount();
/* Scroll into view */
scrolledComp.setOrigin(0, y);
}
});
Use this method to get the y position:
private static int getYPosition(ExpandBar bar, int position)
{
/* Calculate the position */
int y = 0;
for(int i = 0; i < position; i++)
{
/* Incorporate the spacing */
y += bar.getSpacing();
/* Get the item (On LINUX, use this line) */
ExpandItem item = bar.getItem(bar.getItemCount() - 1 - i);
/* Get the item (On WINDOWS, use this line) */
//ExpandItem item = bar.getItem(i);
/* Add the header height */
y += item.getHeaderHeight();
/* If the item is expanded, add it's height as well */
if(item.getExpanded())
y += item.getHeight();
}
return y;
}

SWT table row mousehandler and checkbox detection

When clicking a row a window pops up.
When clicking the cell in the first column nothing happens because a checkbox is located in the first column and a mouselistener detects the cell in the first column.
But selecting the checkbox the window pops up again.
How can i prevent the window popping up when selecting the checkbox?
public class Testtable {
static Display display;
static Shell shell;
static Font small_font;
public Testtable(){}
public static void main(String args[]){
display = new Display();
small_font = new Font(Display.getDefault(), Display.getDefault().getSystemFont().getFontData() );
shell = new Shell(display, SWT.BORDER|SWT.PRIMARY_MODAL|SWT.RESIZE);
shell.setText(" Test table ");
shell.setLayout(new GridLayout(1, true));
final Table table = new Table(shell, SWT.BORDER | SWT.CHECK | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setFont(small_font);
GridData griddata = new GridData(SWT.FILL, SWT.FILL,false,false);
griddata.horizontalSpan=5;
griddata.heightHint = table.getItemHeight()*15;
table.setLayoutData(griddata);
TableColumn checkbox = new TableColumn(table,SWT.NONE,0);
TableColumn column_one = new TableColumn(table,SWT.NONE,1);
column_one.setText("column one");
TableColumn column_two = new TableColumn(table,SWT.NONE,2);
column_two.setText("column_two");
TableColumn column_three = new TableColumn(table,SWT.NONE,3);
column_three.setText("column_three");
TableColumn column_four = new TableColumn(table,SWT.NONE,4);
column_four.setText("column_four");
for(int i=0;i<10;i++){
TableItem item=new TableItem(table,SWT.NONE);
item.setText(new String [] {"column 2 item-"+i,"column 3 item-"+i,"column 4 item-"+i});
}
Label labelfiller=new Label(shell, SWT.SHADOW_OUT); /* Filler */
labelfiller.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING,0, true,true,4,2));
Button close = new Button(shell, SWT.PUSH);
close.setText("Done");
shell.setDefaultButton(close);
close.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
close.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shell.dispose();
}
});
for(int i=0;i<table.getColumnCount();i++){
table.getColumn(i).pack();
}
table.addListener(SWT.MouseUp,new Listener(){
public void handleEvent(Event e){
if(table.getItem(new Point(e.x, e.y)).getBounds(0).contains(new Point(e.x, e.y))){
//if((e.widget.getStyle()&32) == SWT.CHECK){
System.out.println("returned cause selected column 0, wich is checkbox column.");
return;
}//}
showFrame();
}
});
table.pack();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!shell.getDisplay().readAndDispatch())
shell.getDisplay().sleep();
}
}
static void showFrame(){
final Shell dialog = new Shell(shell,SWT.BORDER|SWT.PRIMARY_MODAL|SWT.RESIZE);
dialog.setText("Test shell.. ");
dialog.setLayout(new GridLayout(3, true));
Label label = new Label(dialog,SWT.NONE);
label.setText("Row clicked: ");
Button ok = new Button(dialog, SWT.PUSH);
ok.setText("Close");
dialog.setDefaultButton(ok);
ok.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
ok.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
dialog.dispose();
}
});
dialog.pack();
dialog.open();
while (!dialog.isDisposed()) {
if (!dialog.getDisplay().readAndDispatch())
dialog.getDisplay().sleep();
}
}
}
Alright, found a solution.
The problem is, that there is no way (that I'm aware of) which will return the bounds of the checkbox. However, since the checkbox will always be the first thing in the table (if you use a Table with SWT.CHECK), you can simply check if the click event is to the left of the first cell.
I took the liberty to "optimize" some of your other code (my subjective opinion):
public static void main(String args[])
{
Display display = new Display();
final Shell shell = new Shell(display, SWT.BORDER | SWT.PRIMARY_MODAL | SWT.RESIZE);
shell.setText(" Test table ");
shell.setLayout(new GridLayout(1, true));
final Table table = new Table(shell, SWT.BORDER | SWT.CHECK | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
for(int col = 0; col < 5; col++)
{
new TableColumn(table, SWT.NONE).setText("column " + col);
}
for (int row = 0; row < 10; row++)
{
TableItem item = new TableItem(table, SWT.NONE);
for(int col = 1; col < table.getColumnCount(); col++)
{
item.setText(col, "cell " + row + " " + col);
}
}
for(int col = 0; col < table.getColumnCount(); col++)
{
table.getColumn(col).pack();
}
Button close = new Button(shell, SWT.PUSH);
close.setText("Done");
shell.setDefaultButton(close);
close.setLayoutData(new GridData(SWT.FILL, SWT.END, true, false));
close.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event e)
{
shell.dispose();
}
});
table.addListener(SWT.MouseUp, new Listener()
{
public void handleEvent(Event e)
{
if (table.getItemCount() > 0)
{
Rectangle rect = table.getItem(new Point(e.x, e.y)).getBounds(0);
if (rect.contains(new Point(e.x, e.y)) || e.x <= rect.x)
System.out.println("first column or checkbox clicked");
else
System.out.println("other column clicked");
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!shell.getDisplay().readAndDispatch())
shell.getDisplay().sleep();
}
}

Set width of SWT Table Column

I'm adding column one by one to my swt table. with
int totalwidth=0;
for(String s:phoneErrs){
TableColumn tblclmnError = new TableColumn(tablephone, SWT.CENTER);
tblclmnError.setText(s);
tblclmnError.pack();
totalwidth+=tblclmnError.getWidth();
}
and after this I want to add a last column, that should fill the rest of the
space in table header. Now that I have the total width of the added columns
already, I should be able to calculate the width of my last column and specify
it right? but how? I tried
TableColumn tblclmnComment = new TableColumn(tablephone, SWT.CENTER);
tblclmnComment.setWidth(tablephone.getSize().x-totalwidth);
tblclmnComment.setText("Comment");
but it's not working. the getSize() return 0.
You can achieve this by adding listener on SWT.Resize event type.
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, true));
TableViewer viewer1 = getViewer(shell);
List<String> rows = new ArrayList<String>();
rows.add("Row 1");
rows.add("Row 2");
viewer1.setInput(rows);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static TableViewer getViewer(final Shell shell) {
TableViewer viewer = new TableViewer(shell, SWT.FULL_SELECTION
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.NONE);
viewer.getTable().addListener(SWT.Resize, new Listener() {
#Override
public void handleEvent(Event event) {
Table table = (Table)event.widget;
int columnCount = table.getColumnCount();
if(columnCount == 0)
return;
Rectangle area = table.getClientArea();
int totalAreaWdith = area.width;
int lineWidth = table.getGridLineWidth();
int totalGridLineWidth = (columnCount-1)*lineWidth;
int totalColumnWidth = 0;
for(TableColumn column: table.getColumns())
{
totalColumnWidth = totalColumnWidth+column.getWidth();
}
int diff = totalAreaWdith-(totalColumnWidth+totalGridLineWidth);
TableColumn lastCol = table.getColumns()[columnCount-1];
//check diff is valid or not. setting negetive width doesnt make sense.
lastCol.setWidth(diff+lastCol.getWidth());
}
});
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.getTable().setLayoutData(
new GridData(SWT.FILL, SWT.FILL, true, true));
TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
col.getColumn().setWidth(100);
col.getColumn().setText("Text Column");
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public void update(ViewerCell cell) {
cell.setText((String) cell.getElement());
}
});
col = new TableViewerColumn(viewer, SWT.NONE);
col.getColumn().setWidth(100);
col.getColumn().setText("Second Text Column");
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public void update(ViewerCell cell) {
cell.setText((String) cell.getElement());
}
});
viewer.getTable().setHeaderVisible(true);
return viewer;
}

Categories