org.eclipse.core.runtime.AssertionFailedException: assertion failed: - swt

I am trying to create a table with ComboBoxCellEditor column. When I set value that time below exception is coming.
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/............/
public class Test {
public static void main(String[] args) {
Shell shell = new Shell();
shell.setText("TableViewer Example");
GridLayout layout = new GridLayout();
shell.setLayout(layout);
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
composite.setLayout(new GridLayout(1, false));
Table testTable = new Table(composite, SWT.BORDER);
testTable.setLinesVisible(true);
testTable.setHeaderVisible(true);
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, false);
tableData.heightHint = 300;
testTable.setLayoutData(tableData);
TableViewerColumn columnViewer = null;
String[] columnNames = { "Name", "Laptops" };
TableViewer testTableViewer = new TableViewer(testTable);
for (int i = 0; i < columnNames.length; i++) {
columnViewer = new TableViewerColumn(testTableViewer, SWT.LEFT);
columnViewer.getColumn().setText(columnNames[i]);
if (columnNames[i].equals("Name")) {
columnViewer.getColumn().setWidth(200);
} else if (columnNames[i].equals("Laptops")) {
columnViewer.getColumn().setWidth(300);
}
columnViewer.getColumn().setResizable(true);
columnViewer.getColumn().setMoveable(true);
columnViewer.setLabelProvider(new TestColumnLabelProvider(i));
}
testTableViewer.setContentProvider(new TestContentProvider());
testTableViewer.setColumnProperties(columnNames);
TestBean[] testBeans = new TestBean[5];
for (int i = 0; i < 5; i++) {
TestBean bean = new TestBean();
TableViewerColumn[] getTableViewerColumns =
getTableViewerColumns(testTableViewer);
for (int j = 0; j < getTableViewerColumns.length; j++) {
getTableViewerColumns[j].setEditingSupport(new
TestEditingSuport(testTableViewer, j, bean.getListOfLaptop));
}
bean.setName("Debasish" + i);
bean.setLaptop(bean.getListOfLaptop[i]);
testBeans[i] = bean;
}
testTableViewer.setInput(testBeans);
shell.open();
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
public static TableViewerColumn[] getTableViewerColumns(TableViewer
tableViewer) {
TableColumn[] columns = tableViewer.getTable().getColumns();
TableViewerColumn[] viewerColumns = new TableViewerColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
TableColumn tableColumn = columns[i];
viewerColumns[i] = (TableViewerColumn) tableColumn.getData(Policy.JFACE +
".columnViewer");
}
return viewerColumns;
}
}
/............./
class TestBean {
private String name;
private String laptop;
public String[] getListOfLaptop = { "Acer", "HP", "Lenovo", "Dell", "Benq"
};
//getter and setter method
}
/..................../
class TestEditingSuport extends EditingSupport {
private int m_column;
private CellEditor m_editor;
public TestEditingSuport(ColumnViewer viewer, int column,
String[] listOfTestBean) {
super(viewer);
m_column = column;
// Create the correct editor based on the column index
switch (column) {
case 0:
case 1:
m_editor = new ComboBoxCellEditor(
((TableViewer) viewer).getTable(), listOfTestBean);
break;
default:
}
}
#Override
protected CellEditor getCellEditor(Object element) {
return m_editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
TestBean bean = (TestBean) element;
Object value = null;
switch (m_column) {
case 0:
value = bean.getName();
break;
case 1:
value = bean.getLaptop();
break;
default:
}
return value;
}
#Override
protected void setValue(Object element, Object value) {
TestBean bean = (TestBean) element;
switch (m_column) {
case 0:
if (valueChanged(bean.getName(), (String) value)) {
bean.setName((String) value);
}
getViewer().update(bean, null);
break;
case 1:
int index = (Integer) value;
String laptop = bean.getListOfLaptop[index];
if (valueChanged(bean.getLaptop(), laptop)) {
bean.setLaptop(laptop);
}
getViewer().update(bean, null);
break;
default:
}
}
private boolean valueChanged(String previousValue, String currentValue) {
boolean changed = false;
if ((previousValue == null) && (currentValue != null)) {
changed = true;
} else if ((previousValue != null) && (currentValue != null) && (!previousValue.equals(currentValue))) {
changed = true;
}
return changed;
}
}
/............../
class TestContentProvider implements IStructuredContentProvider {
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
}
/........................./
class TestColumnLabelProvider extends ColumnLabelProvider {
private int m_column;
public TestColumnLabelProvider(int column) {
this.m_column = column;
}
public String getText(Object element) {
String text = null;
if (element instanceof TestBean) {
TestBean testBean = (TestBean) element;
switch (m_column) {
case 0:
text = testBean.getName();
break;
case 1:
text = testBean.getLaptop();
break;
default:
}
}
return text;
}
}
/....................../

ComboCellEditor values are integer indexes in to the list of values you give it in the constructor.
Your getValue method of your EditingSupport class must return an Integer index in to the values list.
The setValue method of your EditingSupport class will be given an Integer containing the selected index.

Related

assertion failed: Unknown column layout data

When I create combo box in particular only one 3rd column using table viewer in Eclipse SWT.
I think I've done everything ok until now, however when I compile the code then i get error:
Code:
public void createPartControl(Composite parent) {
Composite tableComposite = new Composite(parent, SWT.NONE);
tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
true));
tableViewer = new TableViewer(tableComposite, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
// TODO viewer.setLabelProvider(new ViewLabelProvider());
table = tableViewer.getTable();
// Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Threat Name", "Category Name", "Status",
"Priority", "Description", "Justification" };
int[] bounds = { 100, 100, 100, 100 };
TableViewerColumn col = createTableViewerColumn(titles[2], bounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Dummy p = (Dummy) element;
return p.getValue();
}
});
col.setEditingSupport(new FirstValueEditingSupport(tableViewer));
}
private SelectionAdapter getSelectionAdapter(final TableColumn column,
final int index) {
SelectionAdapter selectionAdapter = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
tableViewer.refresh();
}
};
return selectionAdapter;
}
private static class Dummy {
public String value;
public Dummy(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class FirstValueEditingSupport extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
private final String[] possibleValues = { "Mitigated",
"Not Applicable", "Not Started", "Needs Investigation" };
public FirstValueEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
this.editor = new ComboBoxCellEditor(viewer.getTable(),
possibleValues);
}
#Override
protected CellEditor getCellEditor(Object element) {
return editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
Dummy dummy = (Dummy) element;
int index = 0;
for (int i = 0; i < possibleValues.length; i++) {
if (Objects.equals(possibleValues[i], dummy.getValue())) {
index = i;
break;
}
}
return index;
}
#Override
protected void setValue(Object element, Object value) {
Dummy dummy = (Dummy) element;
int index = (Integer) value;
dummy.setValue(possibleValues[index]);
viewer.update(element, null);
}
}
private void fillRows(String shortdesc, String categ, String descp) {
System.out.println("fillRows call from above method.");
TableColumn status_Name_Col = tableViewer.getTable().getColumn(2);
System.out.println("**************** status_Name_Col ************ "
+ status_Name_Col);
tableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
#Override
public void selectionChanged(
SelectionChangedEvent selectionChangedEvent) {
StructuredSelection selection = (StructuredSelection) selectionChangedEvent
.getSelection();
System.out.println(((Dummy) selection.getFirstElement())
.getValue());
}
});
List<Dummy> elements = new ArrayList<>();
for (int i = 0; i < Connection.Number_Of_Connection; i++) {
elements.add(new Dummy("First option"));
}
tableViewer.setInput(elements);
tableColumnLayout.setColumnData(status_Name_Col, new ColumnWeightData(
1, true));
tableViewerColumn.setEditingSupport(new FirstValueEditingSupport(
tableViewer));
}
Questions:
how to display combo box in particular only one column?
You must not do the TableViewer setInput call until you have set up everything on the table. All the content providers, label providers, column layouts, editing support, .... must be set before setInput is called.
You must also call setColumnData for every column you create.

How do i get The answers selected in testFragment which is set in the customlistadapter?

This is my testfragment where i build the list based on a switch:
public class TestFragment extends Fragment {
public String Workshop;
public int NumberOfQuestions;
public Button SaveButton;
public TextView GradeView;
public String Grades;
private OnFragmentInteractionListener mListener;
public TestFragment() {}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle bundle){
View rootView = inflater.inflate(R.layout.questionscomplete,
container, false);
Workshop = getArguments().getString("Workshoptitle");
GradeView = ((TextView) rootView.findViewById(R.id.GradeView));
// Inflate the layout for this fragment
if (!Workshop.equals("Doodlz Drawing")) {
rootView = inflater.inflate(R.layout.fragment_test,
container, false);
final ListView lv1 = (ListView) rootView.findViewById(R.id.listview);
ArrayList image_details = getListData();
lv1.setAdapter(new CustomListAdapter(getActivity(), image_details));
SaveButton = ((Button) rootView.findViewById(R.id.Save));
SaveButton.setOnClickListener(Grading);
}
return rootView;
}
private ArrayList getListData() {
ArrayList<QuestionItem> results = new ArrayList<QuestionItem>();
switch (Workshop) {
case "Android Studio":
Workshop = "Android Studio";
QuestionItem[] Item1 = new QuestionItem[3];
QItem WS1 = new QItem();
NumberOfQuestions = Item1.length;
String[] WS1Q = WS1.getQuestions(Workshop, NumberOfQuestions);
String[] WS1QA = WS1.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item1[i] = new QuestionItem();
Item1[i].setQuestion(WS1Q[i]);
Item1[i].setAnswer1(WS1QA[i * 10 + 0]);
Item1[i].setAnswer2(WS1QA[i * 10 + 1]);
Item1[i].setAnswer3(WS1QA[i * 10 + 2]);
Item1[i].setAnswer4(WS1QA[i * 10 + 3]);
// Toast.makeText(getActivity(), Item1[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
results.add(Item1[i]);
}
break;
case "Java Basics":
Workshop = "Java Basics";
QuestionItem[] Item2 = new QuestionItem[5];
QItem WS2 = new QItem();
NumberOfQuestions = Item2.length;
String[] WS2Q = WS2.getQuestions(Workshop, NumberOfQuestions);
String[] WS2QA = WS2.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item2[i] = new QuestionItem();
Item2[i].setQuestion(WS2Q[i]);
Item2[i].setAnswer1(WS2QA[i * 10 + 0]);
Item2[i].setAnswer2(WS2QA[i * 10 + 1]);
Item2[i].setAnswer3(WS2QA[i * 10 + 2]);
Item2[i].setAnswer4(WS2QA[i * 10 + 3]);
results.add(Item2[i]);
// Toast.makeText(getActivity(), Item2[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
}
break;
My listadapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public String Answer;
public String[] Answers;
private ArrayList<QuestionItem> listData;
public CustomListAdapter(Context aContext, ArrayList<QuestionItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.questions, null);
holder = new ViewHolder(
);
holder.QuestionView = (TextView) convertView.findViewById(R.id.q);
holder.Answer1View = (TextView) convertView.findViewById(R.id.qa1);
holder.Answer2View = (TextView) convertView.findViewById(R.id.qa2);
holder.Answer3View = (TextView) convertView.findViewById(R.id.qa3);
holder.Answer4View = (TextView) convertView.findViewById(R.id.qa4);
//
holder.Answer1Button = (RadioButton) convertView.findViewById(R.id.qa1);
holder.Answer2Button = (RadioButton) convertView.findViewById(R.id.qa2);
holder.Answer3Button = (RadioButton) convertView.findViewById(R.id.qa3);
holder.Answer4Button = (RadioButton) convertView.findViewById(R.id.qa4);
holder.ButtonGroupView = (RadioGroup) convertView.findViewById(R.id.group);
convertView.setTag(holder);
holder.ButtonGroupView.getCheckedRadioButtonId();
holder.ButtonGroupView
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
QuestionItem element = listData.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.qa1:
element.setAnswer("1");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa2:
element.setAnswer("2");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa3:
element.setAnswer("3");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa4:
element.setAnswer("4");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
default:
element.setAnswer(null); // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
QuestionItem element = (QuestionItem) getItem(position);
holder.QuestionView.setText(listData.get(position).getQuestion());
holder.Answer1View.setText(listData.get(position).Getanswer1());
holder.Answer2View.setText(listData.get(position).Getanswer2());
holder.Answer3View.setText(listData.get(position).Getanswer3());
holder.Answer4View.setText(listData.get(position).Getanswer4());
holder.ButtonGroupView.setTag(new Integer(position)); // I passed the current position as a tag
return convertView;
}
//
class ViewHolder {
TextView t = null;
TextView QuestionView;
TextView Answer1View;
TextView Answer2View;
TextView Answer3View;
TextView Answer4View;
RadioButton Answer1Button, Answer2Button, Answer3Button, Answer4Button;
RadioGroup ButtonGroupView;
}}
My question Item:
public class QuestionItem {
private String Question;
private String Answer1;
private String Answer2;
private String Answer3;
private String Answer4;
private String Answer;
public String getQuestion() {
return Question;
}
public void setQuestion(String Question) {
this.Question = Question;
}
public String Getanswer1() {
return Answer1;
}
public void setAnswer1(String Answer1) {
this.Answer1 = Answer1;
}
public String Getanswer2() {
return Answer2;
}
public void setAnswer2(String Answer2) {
this.Answer2 = Answer2;
}
public String Getanswer3() {
return Answer3;
}
public void setAnswer3(String Answer3) {
this.Answer3 = Answer3;
}
public String Getanswer4() {
return Answer4;
}
public void setAnswer4(String Answer4) {
this.Answer4 = Answer4;
}
public String GetAnswer() {
return Answer;
}
public void setAnswer(String Answer) {
this.Answer = Answer;
}
}
I want to save all the answers and compare them to the right answers and save the score to be used as a variable in another fragment.
UPDATE: added "Log.d(listData.get(pos).toString(), element.GetAnswer());" And i can see it is storing the choses answers so how do i request them in the testfragment and check them
Ive tried several things but cannot find the solution. pls help:)?

Enabling single column selection in org.eclipse.swt.widgets.Table

I have used the org.eclipse.swt.widgets.Table
Code implementation will look like this
Table table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
But i need behavior like if mouse clicked on 'Sec_1' i want only 'Sec_1' to be selected not entire row and if mouse clicked on 'First_1' i don't want it to be Highlighted(FirstColumn no selection).
Can any one help me ?
Please see this code snippet for example (http://git.eclipse.org/c/platform/eclipse.platform.ui.git/tree/examples/org.eclipse.jface.snippets/Eclipse%20JFace%20Snippets/org/eclipse/jface/snippets/viewers/Snippet036FocusBorderCellHighlighter.java):
public class Test {
private class MyContentProvider implements IStructuredContentProvider {
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return (MyModel[]) inputElement;
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public static boolean flag = true;
public class MyModel {
public int counter;
public MyModel(int counter) {
this.counter = counter;
}
public String toString() {
return "Item " + this.counter;
}
}
public class MyLabelProvider extends LabelProvider implements
ITableLabelProvider, ITableFontProvider, ITableColorProvider {
FontRegistry registry = new FontRegistry();
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
return "Column " + columnIndex + " => " + element.toString();
}
public Font getFont(Object element, int columnIndex) {
return null;
}
public Color getBackground(Object element, int columnIndex) {
return null;
}
public Color getForeground(Object element, int columnIndex) {
return null;
}
}
public Test(Shell shell) {
final TableViewer v = new TableViewer(shell, SWT.BORDER|SWT.FULL_SELECTION);
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setCellEditors(new CellEditor[] { new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()) });
v.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
return "Column " + property + " => " + element.toString();
}
public void modify(Object element, String property, Object value) {
}
});
v.setColumnProperties(new String[] {"1","2","3"});
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(v,new FocusCellOwnerDrawHighlighter(v));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(v) {
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(v, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
TableColumn column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 1");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 2");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 3");
MyModel[] model = createModel();
v.setInput(model);
v.getTable().setLinesVisible(true);
v.getTable().setHeaderVisible(true);
}
private MyModel[] createModel() {
MyModel[] elements = new MyModel[10];
for (int i = 0; i < 10; i++) {
elements[i] = new MyModel(i);
}
return elements;
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Test(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

GWT sinkEvents in hosted mode

I extends a gwt celltable to create a custom celltable, i register the sinkevents ie onmouseover/onmouseout.
when you hover on the row of the table the row data is populated on the hover wiget(custom hover popup panel).
its works as it supose to do on development mode but once deployed on tomcat when you move the mouse over different rows on the celltable it
does not update the hover data on the popup panel unless you click away from the table(loose focus) and the hover again on the row.
public class MyCellTable<T> extends CellTable<T> {
private Tooltip popup = new Tooltip();
private List<String> tooltipHiddenColumn = new ArrayList<String>();
private boolean showTooltip;
public MyCellTable() {
super();
sinkEvents(Event.ONMOUSEOVER | Event.ONMOUSEOUT);
}
#Override
public void onBrowserEvent2(Event event) {
super.onBrowserEvent2(event);
if (isShowTooltip()) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOUT: {
popup.hide(true);
break;
}
case Event.ONMOUSEOVER: {
popup.setAutoHideEnabled(true);
showToolTip(event);
break;
}
}
}
}
private void showToolTip(final Event event) {
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
final Element target = event.getEventTarget().cast();
// Find the cell where the event occurred.
TableCellElement tableCell = findNearestParentCell(target);
if (tableCell == null) {
return;
}
Element trElem = tableCell.getParentElement();
if (trElem == null) {
return;
}
TableRowElement tr = TableRowElement.as(trElem);
Element sectionElem = tr.getParentElement();
if (sectionElem == null) {
return;
}
TableSectionElement section = TableSectionElement.as(sectionElem);
if (section == getTableHeadElement()) {
return;
}
NodeList<TableCellElement> cellElements = tr.getCells().cast();
NodeList<TableCellElement> headers = getTableHeadElement().getRows().getItem(0).getCells().cast();
popup.getGrid().clear(true);
popup.getGrid().resizeRows(cellElements.getLength());
for (int i = 0; i < cellElements.getLength(); i++) {
if (getTooltipHiddenColumn().indexOf(headers.getItem(i).getInnerHTML()) == -1) {
TableCellElement tst = TableCellElement.as(cellElements.getItem(i));
popup.getGrid().setHTML(i, 0, headers.getItem(i).getInnerHTML());
popup.getGrid().setHTML(i, 1, tst.getInnerHTML());
}
}
// Here the constant values are used to give some gap between mouse pointer and popup panel
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = event.getClientX() + 5;
int top = event.getClientY() + 5;
if ((offsetHeight + top + 20) > Window.getClientHeight()) {
top = top - offsetHeight - 10;
}
popup.setPopupPosition(left, top);
}
});
popup.show();
}
public ArrayList<ReorderColumnsDetails> getColumnsHeaders(int index){
ArrayList<ReorderColumnsDetails> column = new ArrayList<ReorderColumnsDetails>();
NodeList<TableCellElement> headers = getTableHeadElement().getRows().getItem(0).getCells().cast();
for (int i = 0; i < index; i++) {
ReorderColumnsDetails clm = new ReorderColumnsDetails();
clm.setHearder(headers.getItem(i).getInnerHTML().toString());
clm.setItemIndex(i);
column.add(clm);
}
return column;
}
private TableCellElement findNearestParentCell(Element elem) {
while ((elem != null) && (elem != getElement())) {
String tagName = elem.getTagName();
if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) {
return elem.cast();
}
elem = elem.getParentElement();
}
return null;
}
/**
* Specify Name of the column's which is not to shown in the Tooltip
*/
public List<String> getTooltipHiddenColumn() {
return tooltipHiddenColumn;
}
/**
* Set title to tooltip
*
* #param title
*/
public void setTooltipTitle(String title) {
popup.setHTML(title);
}
public boolean isShowTooltip() {
return showTooltip;
}
public void setShowTooltip(boolean showTooltip) {
this.showTooltip = showTooltip;
}
}

Making a drag and drop FlexTable in GWT 2.5

I'm trying to make a simple Drag and Drop FlexTable using native GWT drag events to allow the user to move rows around.
//This works fine
galleryList.getElement().setDraggable(Element.DRAGGABLE_TRUE);
galleryList.addDragStartHandler(new DragStartHandler() {
#Override
public void onDragStart(DragStartEvent event) {
event.setData("text", "Hello World");
groupList.getElement().getStyle().setBackgroundColor("#aff");
}
});
However, I'd like to:
1. Give a visual indicator where the item will be dropped.
2. Work out where i should drop the row, when the drop event fires.
galleryList.addDragOverHandler(new DragOverHandler() {
#Override
public void onDragOver(DragOverEvent event) {
//TODO: How do i get the current location one would drop an item into a flextable here
}
});
galleryList.addDragEndHandler(new DragEndHandler() {
#Override
public void onDragEnd(DragEndEvent event) {
//TODO: How do i know where i am in the flextable
}
});
I see these FlexTable methods are useful in getting a cell/row:
public Cell getCellForEvent(ClickEvent event)
protected Element getEventTargetCell(Event event)
But the problem is the Drag events do not inherit of Event
Thanks in advance
Caveat: I cant gaurentee this will work out the box. This is the code I ended up making (And works for me) - it's a Drag n Drop Widget which inherits from FlexTable. I detect any drag events on the table, and then try compute where the mouse is over that FlexTable.
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;
public class DragFlexTable extends FlexTable implements DraggableWidget {
public String dragStyle = "drag-table-row";
public String dragReplaceStyle;
protected DragVerticalHandler dragFlexTableHandler;
private int currentRow;
private int[] yLocations;
private int rowBeingDragged;
DragFlexTable() {
sinkEvents(Event.ONMOUSEOVER | Event.ONMOUSEOUT);
getElement().setDraggable(Element.DRAGGABLE_TRUE);
final DragUtil dragUtil = new DragUtil();
addDragStartHandler(new DragStartHandler() {
#Override
public void onDragStart(DragStartEvent event) {
dragUtil.startVerticalDrag(event, DragFlexTable.this);
}
});
addDragEndHandler(new DragEndHandler() {
#Override
public void onDragEnd(DragEndEvent event) {
dragUtil.endVerticalDrag(event, DragFlexTable.this);
}
});
addDragOverHandler(new DragOverHandler() {
#Override
public void onDragOver(DragOverEvent event) {
dragUtil.handleVerticalDragOver(event, DragFlexTable.this, 3);
}
});
}
#Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
Element td = getEventTargetCell(event);
if (td == null) return;
Element tr = DOM.getParent(td);
currentRow = TableRowElement.as(td.getParentElement()).getSectionRowIndex();
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER: {
//tr.addClassName(ROW_STYLE_NAME + "-mouseover");
tr.addClassName(dragStyle);
break;
}
case Event.ONMOUSEOUT: {
tr.removeClassName(dragStyle);
break;
}
}
}
public void setDragStyle(String dragStyle) {
this.dragStyle = dragStyle;
}
#Override
public void resetDragState() {
yLocations = null;
}
#Override
public void setRowBeingDragged(int currentRow) {
this.rowBeingDragged = currentRow;
}
#Override
public int getDragRow(DragDropEventBase event) {
if (yLocations == null) {
yLocations = new int[getRowCount()];
for (int i = 0; i < getRowCount(); i++) {
Widget widget = getWidget(i, 0);
if (widget.isVisible()) {
com.google.gwt.dom.client.Element imgTd = widget.getElement().getParentElement();
int absoluteBottom = imgTd.getAbsoluteBottom();
yLocations[i] = absoluteBottom;
} else {
yLocations[i] = -1;
}
}
}
int lastY = 0;
for (int i = 0; i < yLocations.length; i++) {
int absoluteBottom = yLocations[i];
//invisible
if (absoluteBottom != -1) {
int absoluteTop = lastY;
int clientY = event.getNativeEvent().getClientY();
if (absoluteBottom > clientY && absoluteTop < clientY) {
//com.google.gwt.dom.client.Element tr = imgTd.getParentElement();
return i;
}
lastY = absoluteBottom;
}
}
return currentRow;
}
#Override
public com.google.gwt.dom.client.Element getTrElement(int row) {
return getWidget(row, 0).getElement().getParentElement().getParentElement();
}
#Override
public DragVerticalHandler getDragFlexTableHandler() {
return dragFlexTableHandler;
}
public void setDragReplaceStyle(String dragReplaceStyle) {
this.dragReplaceStyle = dragReplaceStyle;
}
#Override
public int getRowBeingDragged() {
return rowBeingDragged;
}
#Override
public String getDragReplaceStyle() {
return dragReplaceStyle;
}
public void setDragFlexTableHandler(DragVerticalHandler dragFlexTableHandler) {
this.dragFlexTableHandler = dragFlexTableHandler;
}
}
This is util class which it uses
import com.google.gwt.event.dom.client.DragEndEvent;
import com.google.gwt.event.dom.client.DragOverEvent;
import com.google.gwt.event.dom.client.DragStartEvent;
import com.google.gwt.user.client.ui.Image;
public class DragUtil {
private int alternateIgnoreEvent = 0;
private int lastDragRow = -1;
public void startVerticalDrag(DragStartEvent event, DraggableWidget widget) {
widget.resetDragState();
//Required
event.setData("text", "dragging");
int currentRow = widget.getDragRow(event);
widget.setRowBeingDragged(currentRow);
if (widget.getDragFlexTableHandler()!=null) {
Image thumbnailImg = widget.getDragFlexTableHandler().getImage(currentRow);
if (thumbnailImg!=null) {
event.getDataTransfer().setDragImage(thumbnailImg.getElement(), -10, -10);
}
}
}
public void handleVerticalDragOver(DragOverEvent event, DraggableWidget widgets, int sensitivity) {
if (alternateIgnoreEvent++ % sensitivity != 0) {
//many events fire, for every pixel move, which slow the browser, so ill ignore some
return;
}
int dragRow = widgets.getDragRow(event);
if (dragRow != lastDragRow) {
com.google.gwt.dom.client.Element dragOverTr = widgets.getTrElement(dragRow);
if (lastDragRow != -1) {
com.google.gwt.dom.client.Element lastTr = widgets.getTrElement(lastDragRow);
lastTr.removeClassName(widgets.getDragReplaceStyle());
}
lastDragRow = dragRow;
dragOverTr.addClassName(widgets.getDragReplaceStyle());
}
}
public void endVerticalDrag(DragEndEvent event, DraggableWidget widgets) {
int newRowPosition = widgets.getDragRow(event);
//cleanup last position
if (newRowPosition != lastDragRow) {
com.google.gwt.dom.client.Element lastTr = widgets.getTrElement(lastDragRow);
lastTr.removeClassName(widgets.getDragReplaceStyle());
}
if (newRowPosition != widgets.getRowBeingDragged()) {
com.google.gwt.dom.client.Element dragOverTr = widgets.getTrElement(newRowPosition);
dragOverTr.removeClassName(widgets.getDragReplaceStyle());
widgets.getDragFlexTableHandler().moveRow(widgets.getRowBeingDragged(), newRowPosition);
}
}
}
In the uibinder I then use it like this:
<adminDnd:DragFlexTable ui:field='itemFlexTable' styleName='{style.table}' cellSpacing='0'
cellPadding='0'
dragStyle='{style.drag-table-row-mouseover}'
dragReplaceStyle='{style.drag-replace-table-row}'
/>
Even i had this problem and after a little prototyping this is what I ended up with
.I created a class which extended the flex table.Here is the code
public class DragFlexTable extends FlexTable implements
MouseDownHandler,MouseUpHandler,MouseMoveHandler,
MouseOutHandler
{
private int row,column,draggedrow,draggedcolumn;
private Element td;
private Widget w;
private boolean emptycellclicked;
DragFlexTable()
{
sinkEvents(Event.ONMOUSEOVER | Event.ONMOUSEOUT | Event.ONMOUSEDOWN | Event.ONMOUSEMOVE);
this.addMouseDownHandler(this);
this.addMouseMoveHandler(this);
this.addMouseUpHandler(this);
this.addMouseOutHandler(this);
}
#Override
public void onBrowserEvent(Event event)
{
super.onBrowserEvent(event);
td = getEventTargetCell(event);
if (td == null)
{
return;
}
Element tr = DOM.getParent((com.google.gwt.user.client.Element) td);
Element body = DOM.getParent((com.google.gwt.user.client.Element) tr);
row = DOM.getChildIndex((com.google.gwt.user.client.Element) body, (com.google.gwt.user.client.Element) tr);//(body, tr);
column = DOM.getChildIndex((com.google.gwt.user.client.Element) tr, (com.google.gwt.user.client.Element) td);
}
boolean mousedown;
#Override
public void onMouseDown(MouseDownEvent event)
{
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT)
{
//to ensure empty cell is not clciked
if (!td.hasChildNodes())
{
emptycellclicked = true;
}
event.preventDefault();
start(event);
mousedown = true;
}
}
#Override
public void onMouseMove(MouseMoveEvent event)
{
if (mousedown)
{
drag(event);
}
}
#Override
public void onMouseUp(MouseUpEvent event)
{
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT)
{
if (!emptycellclicked)
{
end(event);
}
emptycellclicked = false;
mousedown = false;
}
}
#Override
public void onMouseOut(MouseOutEvent event)
{
this.getCellFormatter().getElement(row, column).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(row, column).getStyle().clearBorderColor();
this.getCellFormatter().getElement(row, column).getStyle().clearBorderWidth();
w.getElement().getStyle().setOpacity(1);
mousedown = false;
}
private void start(MouseDownEvent event)
{
w = this.getWidget(row, column);
w.getElement().getStyle().setOpacity(0.5);
}
private void drag(MouseMoveEvent event)
{
if (draggedrow != row || draggedcolumn != column)
{
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderColor();
this.getCellFormatter().getElement(draggedrow, draggedcolumn).getStyle().clearBorderWidth();
this.draggedrow = row;
this.draggedcolumn = column;
this.getCellFormatter().getElement(row, column).getStyle().setBorderStyle(BorderStyle.DASHED);
this.getCellFormatter().getElement(row, column).getStyle().setBorderColor("black");
this.getCellFormatter().getElement(row, column).getStyle().setBorderWidth(2, Unit.PX);
}
}
private void end(MouseUpEvent event)
{
insertDraggedWidget(row, column);
}
private void insertDraggedWidget(int r,int c)
{
this.getCellFormatter().getElement(r, c).getStyle().clearBorderStyle();
this.getCellFormatter().getElement(r, c).getStyle().clearBorderColor();
this.getCellFormatter().getElement(r, c).getStyle().clearBorderWidth();
w.getElement().getStyle().setOpacity(1);
if (this.getWidget(r, c) != null)
{
//pushing down the widgets already in the column
// int widgetheight = (this.getWidget(r, c).getOffsetHeight() / 2) + this.getWidget(r, c).getAbsoluteTop();
// int rw;
//placing the widget above the dropped widget
for (int i = this.getRowCount() - 1; i >= r; i--)
{
if (this.isCellPresent(i, c))
{
this.setWidget(i + 1, c, this.getWidget(i, c));
}
}
}
this.setWidget(r, c, w);
//removes unneccesary blank rows
cleanupRows();
//pushing up the column in the stack
// for (int i = oldrow;i<this.getRowCount()-1 ;i++)
// {
//
// this.setWidget(i ,oldcolumn, this.getWidget(i+1, oldcolumn));
//
// }
}
private void cleanupRows()
{
ArrayList<Integer> rowsfilled = new ArrayList<Integer>();
for (int i = 0; i <= this.getRowCount() - 1; i++)
{
for (int j = 0; j <= this.getCellCount(i) - 1; j++)
{
if (this.getWidget(i, j) != null)
{
rowsfilled.add(i);
break;
}
}
}
//replace the empty rows
for (int i = 0; i < rowsfilled.size(); i++)
{
int currentFilledRow = rowsfilled.get(i);
if (i != currentFilledRow)
{
for (int j = 0; j < this.getCellCount(currentFilledRow); j++)
{
this.setWidget(i, j, this.getWidget(currentFilledRow, j));
}
}
}
for (int i = rowsfilled.size(); i < this.getRowCount(); i++)
{
this.removeRow(i);
}
}
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler)
{
return addDomHandler(handler, MouseUpEvent.getType());
}
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler)
{
return addDomHandler(handler, MouseDownEvent.getType());
}
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler)
{
return addDomHandler(handler, MouseMoveEvent.getType());
}
public HandlerRegistration addMouseOutHandler(MouseOutHandler handler)
{
return addDomHandler(handler, MouseOutEvent.getType());
}
}
and the on module load for the above custom widget is
public void onModuleLoad()
{
Label a = new Label("asad");
Label b = new Label("ad");
Label c = new Label("qwad");
Label w = new Label("zxd");
a.setPixelSize(200, 200);
a.getElement().getStyle().setBorderStyle(BorderStyle.SOLID);
a.getElement().getStyle().setBorderWidth(1, Unit.PX);
b.setPixelSize(200, 200);
c.setPixelSize(200, 200);
w.setPixelSize(200, 200);
a.getElement().getStyle().setBackgroundColor("red");
b.getElement().getStyle().setBackgroundColor("yellowgreen");
c.getElement().getStyle().setBackgroundColor("lightblue");
w.getElement().getStyle().setBackgroundColor("grey");
DragFlexTable d = new DragFlexTable();
d.setWidget(0, 0, a);
d.setWidget(0, 1, b);
d.setWidget(1, 0, c);
d.setWidget(1, 1, w);
d.setCellPadding(20);
RootPanel.get().add(d);
}