Making a drag and drop FlexTable in GWT 2.5 - gwt

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

Related

Passing values from android to flutter but not from main activity

i'm implementing a third party android sdk in flutter and i want a message to be passed from android to flutter when sdk starts
i have implemented the sdk using platform channel just need to work on the callback code. In the code there is a function called onChannelJoin i want to send message to flutter when this function is called
Main Activity
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
final String CHANNEL = "samples.flutter.io/screen_record";
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
// TODO
if (call.method.equals("startScreenShare")) {
Intent intent = new Intent(MainActivity.this , HelloAgoraScreenSharingActivity.class);
startActivity(intent);
} else {
result.notImplemented();
}
}
});
}
}
ScreenSharingActivity
public class HelloAgoraScreenSharingActivity extends Activity {
private static final String LOG_TAG = "AgoraScreenSharing";
private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
private ScreenCapture mScreenCapture;
private GLRender mScreenGLRender;
private RtcEngine mRtcEngine;
private boolean mIsLandSpace = false;
private void initModules() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (mScreenGLRender == null) {
mScreenGLRender = new GLRender();
}
if (mScreenCapture == null) {
mScreenCapture = new ScreenCapture(getApplicationContext(), mScreenGLRender, metrics.densityDpi);
}
mScreenCapture.mImgTexSrcConnector.connect(new SinkConnector<ImgTexFrame>() {
#Override
public void onFormatChanged(Object obj) {
Log.d(LOG_TAG, "onFormatChanged " + obj.toString());
}
#Override
public void onFrameAvailable(ImgTexFrame frame) {
Log.d(LOG_TAG, "onFrameAvailable " + frame.toString());
if (mRtcEngine == null) {
return;
}
AgoraVideoFrame vf = new AgoraVideoFrame();
vf.format = AgoraVideoFrame.FORMAT_TEXTURE_OES;
vf.timeStamp = frame.pts;
vf.stride = frame.mFormat.mWidth;
vf.height = frame.mFormat.mHeight;
vf.textureID = frame.mTextureId;
vf.syncMode = true;
vf.eglContext14 = mScreenGLRender.getEGLContext();
vf.transform = frame.mTexMatrix;
mRtcEngine.pushExternalVideoFrame(vf);
}
});
mScreenCapture.setOnScreenCaptureListener(new ScreenCapture.OnScreenCaptureListener() {
#Override
public void onStarted() {
Log.d(LOG_TAG, "Screen Record Started");
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
switch (err) {
case ScreenCapture.SCREEN_ERROR_SYSTEM_UNSUPPORTED:
break;
case ScreenCapture.SCREEN_ERROR_PERMISSION_DENIED:
break;
}
}
});
WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
int screenWidth = wm.getDefaultDisplay().getWidth();
int screenHeight = wm.getDefaultDisplay().getHeight();
if ((mIsLandSpace && screenWidth < screenHeight) ||
(!mIsLandSpace) && screenWidth > screenHeight) {
screenWidth = wm.getDefaultDisplay().getHeight();
screenHeight = wm.getDefaultDisplay().getWidth();
}
setOffscreenPreview(screenWidth, screenHeight);
if (mRtcEngine == null) {
try {
mRtcEngine = RtcEngine.create(getApplicationContext(), "Agora_id", new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
Log.d(LOG_TAG, "onJoinChannelSuccess " + channel + " " + elapsed);
}
#Override
public void onWarning(int warn) {
Log.d(LOG_TAG, "onWarning " + warn);
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
}
#Override
public void onAudioRouteChanged(int routing) {
Log.d(LOG_TAG, "onAudioRouteChanged " + routing);
}
});
} catch (Exception e) {
Log.e(LOG_TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
mRtcEngine.enableVideo();
if (mRtcEngine.isTextureEncodeSupported()) {
mRtcEngine.setExternalVideoSource(true, true, true);
} else {
throw new RuntimeException("Can not work on device do not supporting texture" + mRtcEngine.isTextureEncodeSupported());
}
mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, true);
mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
}
}
private void deInitModules() {
RtcEngine.destroy();
mRtcEngine = null;
if (mScreenCapture != null) {
mScreenCapture.release();
mScreenCapture = null;
}
if (mScreenGLRender != null) {
mScreenGLRender.quit();
mScreenGLRender = null;
}
}
/**
* Set offscreen preview.
*
* #param width offscreen width
* #param height offscreen height
* #throws IllegalArgumentException
*/
public void setOffscreenPreview(int width, int height) throws IllegalArgumentException {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Invalid offscreen resolution");
}
mScreenGLRender.init(width, height);
}
private void startCapture() {
mScreenCapture.start();
}
private void stopCapture() {
mScreenCapture.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_agora_screen_sharing);
}
public void onLiveSharingScreenClicked(View view) {
Button button = (Button) view;
boolean selected = button.isSelected();
button.setSelected(!selected);
if (button.isSelected()) {
initModules();
startCapture();
String channel = "ss_test" + System.currentTimeMillis();
channel = "ss_test";
button.setText("stop");
mRtcEngine.muteAllRemoteAudioStreams(true);
mRtcEngine.muteAllRemoteVideoStreams(true);
mRtcEngine.joinChannel(null, channel, "", 0);
} else {
button.setText("start");
mRtcEngine.leaveChannel();
stopCapture();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
deInitModules();
}
}
Dart Code
const platform = const MethodChannel('samples.flutter.io/screen_record');
try {
final int result = await platform.invokeMethod('startScreenShare');
} on PlatformException catch (e) {}
setState(() {
});

JavaFX TableView with Custom Cell Datepicker "OnEditCommit" is not invoked

Hi everyone !!
I'm working with JavaFX and the JDK 8.
I got a TableView filled by a database with the use of a JavaFX POJO Class "Inputs". I've implemented TexField cells, ComboBoxes cells and Checkbox cells succesfully.
But I am not able to make it working with DatePicker Control: the event on the "setOnEditComit" is never invoked...
Hre is my code:
Declarations for TableColumn:
#FXML
private TableColumn<Inputs,LocalDate> colDate = new TableColumn<Inputs,LocalDate>();
[...]
colDate.setCellValueFactory(
new PropertyValueFactory<Inputs,LocalDate>("localdate"));
Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>> dateCellFactory =
new Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>>() {
public TableCell call(TableColumn p) {
return new EditingDatePickerCell();
}
};
[...]
colDate.setOnEditCommit(
new EventHandler<CellEditEvent<Inputs, LocalDate>>() {
#Override
public void handle(CellEditEvent<Inputs, LocalDate> event) {
System.out.println("EVENT!!!!");
((Inputs) event.getTableView().getItems().get(
event.getTablePosition().getRow())
).setDatePicker(event.getNewValue());
}
}
);
With these JavaFX POJO Objects declarations:
public ObjectProperty<LocalDate> localdate;
[...]
this.localdate = new SimpleObjectProperty<LocalDate>(localdate);
[...]
public LocalDate getDatePicker() {
return localdate.getValue();
}
[...]
public void setDatePicker(LocalDate value) {
System.out.println("EVENT!!!!");
localdate.setValue(value);
}
[...]
public ObjectProperty<LocalDate> localdateProperty() {
return localdate;
}
EditingDatePickerCell class:
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import com.desktop.newapp.utils.Inputs;
public class EditingDatePickerCell <Inputs, LocalDate> extends TableCell<Inputs, LocalDate> {
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
datePicker.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
datePicker.setValue((java.time.LocalDate) getItem());
setGraphic(null);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
private DatePicker datePicker;
public EditingDatePickerCell() {
if (datePicker == null) {
createDatePicker();
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (datePicker != null && item != null) {
datePicker.setValue((java.time.LocalDate) getLocalDate());
commitEdit(getLocalDate());
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
private void createDatePicker() {
datePicker = new DatePicker();
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
setGraphic(datePicker);
datePicker.addEventFilter(KeyEvent.KEY_PRESSED,new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(getLocalDate());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitEdit(getLocalDate());;
}
}
});
setAlignment(Pos.CENTER);
}
private LocalDate getLocalDate() {
return getItem();
///return datePicker.getValue() != null ? datePicker.getValue() : getItem();
}
}
I've been Googling a lot and I didn't find any correct implementation of the Java8 DatePicker Editing capabilities in a JavaFX TableView. Any help would be very appreciate !!
Without Stackoverflow I'll never could done the quarter of the whole job so long life to Stackoverflow !!
Regards.
You need to put the table in editing mode (for the current row) when the user interacts with the picker. That can be achieved with an onShowingHandler like this (example is also with a color picker):
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
then watch the valueProperty of the picker like this:
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
For more explanation have a look at my blog post: Custom editor components in JavaFX TableCells.
Full Class:
public class ColorTableCell<T> extends TableCell<T, Color> {
private final ColorPicker colorPicker;
public ColorTableCell(TableColumn<T, Color> column) {
this.colorPicker = new ColorPicker();
this.colorPicker.editableProperty().bind(column.editableProperty());
this.colorPicker.disableProperty().bind(column.editableProperty().not());
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if(empty) {
setGraphic(null);
} else {
this.colorPicker.setValue(item);
this.setGraphic(this.colorPicker);
}
}
}
I was having the same issues but i ended up solving it with this post. JavaFX8 – Render a DatePicker Cell in a TableView.
The outcome is illustrated in the image below.
Your Model object is a bit strange. The setDatePicker and getDatePicker methods should be called setLocaldate and getLocaldate, to be consistent with the localdateProperty() method and (possibly importantly) the parameter passed to the PropertyValueFactory.
I don't think that would cause the problem you observe, though, and I can't see what else is wrong.
This example works for me.
Have a look and see if you can see what I did that's different...
here is a datapicker cell edit when pressing tab key and go to the next cell
datePicker.setOnKeyPressed /EventHandler doesnot work with tab
datePicker.EventFilter get called twice
to work arround this you need to add a listner to tableview cell and get date text as string and cast it to localdate
addEventFilter to TableCell deduction object is a sample
=> addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler() {...}
public class DatePickerCell extends TableCell<Deduction, LocalDate> {
private DatePicker datePicker;
private TableColumn column;
// private TableCell cell;
public DatePickerCell(TableColumn column) { //
super();
this.column = column;
this.datePicker = new DatePicker(getDate());
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
//Platform.runLater(datePicker::requestFocus);
}
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
// SimpleDateFormat smp = new SimpleDateFormat("dd/MM/yyyy");
/* if (null == this.datePicker) {
System.out.println("datePicker is NULL");
}*/ //TO be reviewed
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (datePicker != null) {
datePicker.setValue(getItem());
}
setText(null);
setGraphic(datePicker);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
private LocalDate getDate() {
return getItem() == null ? LocalDate.now() : getItem();
}
private void createDatePicker() {
this.datePicker = new DatePicker(getDate());
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
this.datePicker.editableProperty().bind(column.editableProperty());
this.datePicker.disableProperty().bind(column.editableProperty().not());
this.datePicker.setOnShowing(event -> {
final TableView tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
datePicker.setOnAction((e) -> {
commitEdit(datePicker.getValue());
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
});
datePicker.focusedProperty().addListener(
new ChangeListener<Boolean>() {
#Override
public void changed(
ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(datePicker.getValue());
}
}
});
datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
// System.out.println("setOnKeyPressed datapicker get value ...." + t.getCode());
/* if (t.getCode() == KeyCode.ENTER) {
commitEdit(datePicker.getValue());
System.out.println("Enter datapicker get value " + datePicker.getValue());
} else */if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.ENTER){
commitEdit(datePicker.getValue());
// System.out.println("Tab datapicker get value " + datePicker.getValue());
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
// System.out.println("nextColumn datapicker get value " + nextColumn.getId());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB) {
commitEdit(LocalDate.parse(datePicker.getEditor().getText(), DateTimeFormatter.ofPattern("dd/MM/yyyy")));
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
//
// // setAlignment(Pos.CENTER);
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().toString());
setGraphic(null);
}
public DatePicker getDatePicker() {
return datePicker;
}
public void setDatePicker(DatePicker datePicker) {
this.datePicker = datePicker;
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
private TableColumn<Deduction, ?> getNextColumn(boolean forward) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
for (TableColumn<Deduction, ?> column : getTableView().getColumns()) {
columns.addAll(getLeaves(column));
}
// There is no other column that supports editing.
if (columns.size() < 2) {
return null;
}
int currentIndex = columns.indexOf(getTableColumn());
int nextIndex = currentIndex;
if (forward) {
nextIndex++;
if (nextIndex > columns.size() - 1) {
nextIndex = 0;
}
} else {
nextIndex--;
if (nextIndex < 0) {
nextIndex = columns.size() - 1;
}
}
return columns.get(nextIndex);
}
private List<TableColumn<Deduction, ?>> getLeaves(
TableColumn<Deduction, ?> root) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
if (root.getColumns().isEmpty()) {
// We only want the leaves that are editable.
if (root.isEditable()) {
columns.add(root);
}
return columns;
} else {
for (TableColumn<Deduction, ?> column : root.getColumns()) {
columns.addAll(getLeaves(column));
}
return columns;
}
}
}
in your class with the tableview
Callback cellFactoryDate
= new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new DatePickerCell(p);//DatePickerTest(p) //DatePickerTest2 //EditingCellDate
}
};
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
// dateColumn.setCellFactory(cellFactoryTest);//cellFactoryDate
dateColumn.setCellFactory(cellFactoryDate);
dateColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Deduction, LocalDate>>() {
#Override
public void handle(TableColumn.CellEditEvent<Deduction, LocalDate> t) {
((Deduction) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setDate(t.getNewValue());
}
}
);
Here is a solution acceptable for all custom controls; this example use a ColorPicker control:
So finnaly I deal it like that: on the events of the controls I get back the POJO objects in use by the "((Inputs)getTableView().getItems().get(getTableRow().getIndex()" and I update similary like is it done in the OnEditCommit method...
So for me it's look like this (update the color):
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
Here is example with ColorPickerCell
:
public class ColorPickerTableCell<Inputs> extends TableCell<Inputs, Color>{
private ColorPicker cp;
public ColorPickerTableCell(){
cp = new ColorPicker();
cp.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
commitEdit(cp.getValue());
updateItem(cp.getValue(), isEmpty());
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
}
});
setGraphic(cp);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setEditable(true);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
cp.setVisible(!empty);
this.setItem(item);
cp.setValue(item);
}
}
With this simple JavaFX's POJO:
public ObjectProperty<Color> color = new SimpleObjectProperty<Color>();
this.color = new SimpleObjectProperty(color);
public ObjectProperty<Color> colorProperty() {
return color;
}
public void setColor(Color color2) {
color.set(color2);
}
I do not know if it's a good way to achive that but it worked for me... Note that the JavaFX's POJO is only accessible within an "ActionEvent" request (combobox, datepicker, colorpicker, etc..)
Regards,

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

How to adjust height of richtextbox dynamically based on inner content?

public class AutoResizeBox extends RichTextArea
{
public AutoResizeBox()
{
set(getElement());
}
public static native void set(Element f) /*-{
console.log(f.tagName) ;
// console.log(f.document.body.scrollHeight + 'px');
}-*/;
}
RichTextBox is based on iframe,I tried to use JSNI.For above code,"console.log(f.tagName)" will print out "IFRAME",but "console.log(f.document.body.scrollHeight + 'px');" will preduce a compilation error:"
com.google.gwt.core.client.JavaScriptException: (TypeError): f.document is undefined", can anybody tell me reasons?
Blow is a worked version
import com.google.gwt.dom.client.BodyElement;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.inject.Inject;
public class AutoResizeTextArea extends RichTextArea implements ClickHandler,
BlurHandler
{
private static final int margin = 6;
private BodyElement body;
private String defaultText;
private int minHeight = 25;
private String title;
#Inject
public AutoResizeTextArea()
{
addBlurHandler(this);
addClickHandler(this);
setHeight(minHeight + "px");
setStyleName("textArea");
sinkEvents(Event.ONKEYUP | Event.ONKEYPRESS);
}
private void adjustHeight()
{
// NP remove blow will cause auto-grow doesn't work
if (body != null)
{
int offsetHeight = body.getOffsetHeight();
if (offsetHeight != body.getClientHeight())
{
int height = (offsetHeight < minHeight ? minHeight : offsetHeight);
boolean breaking = height > minHeight;
if (breaking)
{
height = height + margin * 2;
}
setHeight(height + "px");
}
}
}
public void clean()
{
setText(defaultText);
setHeight(minHeight + "px");
setBodyStyle(true);
}
#Override
public String getHTML()
{
// AP RichTextArea.getHTML will return "<br>",even no html exists
// within it,report this issue to gwt team;
String html = super.getHTML();
return html.equals("<br>") || html.equals(defaultText) ? "" : html;
}
#Override
public String getText()
{
String text = super.getText();
return text.equals(defaultText) ? "" : text;
}
#Override
public void onBlur(BlurEvent event)
{
if (defaultText != null && "".equals(getText()))
{
setDefaultText(defaultText);
setBodyStyle(true);
}
}
#Override
public void onBrowserEvent(Event event)
{
super.onBrowserEvent(event);
int eventType = DOM.eventGetType(event);
if (eventType == Event.ONKEYUP || eventType == Event.ONKEYPRESS)
{
adjustHeight();
}
}
#Override
public void onClick(ClickEvent event)
{
super.setText(null);
setBodyStyle(false);
}
private native void registerOnCut(BodyElement element) /*-{
var that = this;
console.log("registerOnCut");
element.oncut = $entry(function(event) {
that.#com.athena.client.ui.richtextbox.AutoResizeTextArea::adjustHeight()();
return false;
});
element.onpaste = $entry(function(event) {
that.#com.athena.client.ui.richtextbox.AutoResizeTextArea::adjustHeight()();
return false;
});
}-*/;
private void setBodyStyle(boolean useDefaultTextStyle)
{
if (body != null)
{
body.setAttribute( "style",
(useDefaultTextStyle ? "color: gray;font-style: italic;" : "")
+ "word-wrap:break-word;overflow:hidden;margin: "
+ margin
+ "px;padding: 0;font-size: 13px;font-family: arial,\"Microsoft YaHei\", Verdana, Tahoma, Arial, STHeiTi,sans-serif, Simsun;");
}
}
public void setDefaultText(String defaultText)
{
super.setText(this.defaultText = defaultText);
}
#Override
public void setHTML(String html)
{
super.setHTML(html);
if (html == null || "".equals(html))
{
setDefaultText(defaultText);
}
adjustHeight();
}
public void setMinHeight(int minHeight)
{
setHeight((this.minHeight = minHeight) + "px");
}
#Override
public void setText(String text)
{
super.setText(text);
if (text == null || "".equals(text))
{
setDefaultText(defaultText);
}
}
#Override
public void setTitle(String title)
{
this.title = title;
}
}

Problem with GWT connector in a straight ended connection

I am trying to make a straight ended connection between widgets.But when I am doing so, the orientation of my connector is coming wrong.Its always coming parallel to the required one.Also , it is independent of the connecting widgets i.e when I move my widget, my connector does not move.Snippet of my code is given as :
Link to snapshot of the problem: http://goo.gl/JUEmJ
public class DragNDropPage {
SyncCurrentUser cu = SyncCurrentUser.getUser();
private AbsolutePanel area = new AbsolutePanel();
HorizontalPanel toolsPanel = new HorizontalPanel();
AbsolutePanel canvas = new AbsolutePanel();
DragController toolboxDragController;
Label startLabel = new Label("START");
Label stopLabel = new Label("STOP");
Label activityLabel = new Label("ACTIVITY");
Label processLabel = new Label("PROCESS");
Button stopDrag = new Button("Done Dragging");
Button saveButton = new Button("Save");
PickupDragController dragController = new PickupDragController(area, true);
AbsolutePositionDropController dropController = new AbsolutePositionDropController(area);
private List<Widget> selected = new ArrayList<Widget>();
private List<Widget> onCanvas = new ArrayList<Widget>();
private List<Connection> connections = new ArrayList<Connection>();
private CActivity[] aItems;
private CProcess[] pItems;
MyHandler handler = new MyHandler();
int mouseX,mouseY;
String style;
public DragNDropPage() {
toolboxDragController = new ToolboxDragController(dropController, dragController);
RootPanel.get("rightbar").add(area);
area.setSize("575px", "461px");
area.add(toolsPanel);
toolsPanel.setSize("575px", "37px");
toolsPanel.add(startLabel);
startLabel.setSize("76px", "37px");
toolboxDragController.makeDraggable(startLabel);
toolsPanel.add(stopLabel);
stopLabel.setSize("66px", "37px");
toolboxDragController.makeDraggable(stopLabel);
toolsPanel.add(activityLabel);
activityLabel.setSize("82px", "36px");
toolboxDragController.makeDraggable(activityLabel);
toolsPanel.add(processLabel);
processLabel.setSize("85px", "36px");
toolboxDragController.makeDraggable(processLabel);
stopDrag.addClickHandler(handler);
toolsPanel.add(stopDrag);
stopDrag.setWidth("114px");
saveButton.addClickHandler(handler);
toolsPanel.add(saveButton);
area.add(canvas, 0, 36);
canvas.setSize("575px", "425px");
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
//46 is the key code for Delete Button
if(event.getNativeEvent().getKeyCode() == 46 && !selected.isEmpty()) {
for (Iterator<Widget> i = selected.listIterator(); i.hasNext();) {
Widget w = (Widget) i.next();
UIObjectConnector.unwrap(w);
i.remove();
w.removeFromParent();
onCanvas.remove(i);
}
}
}
});
aItems = cu.currentUser.getcActivity();
pItems = cu.currentUser.getcProcess();
}
private class ToolboxDragController extends PickupDragController {
public ToolboxDragController(final DropController dropController, final DragController nodesDragController) {
super(area ,false);
setBehaviorDragProxy(true);
registerDropController(dropController);
addDragHandler(new DragHandlerAdapter(){
public void onPreviewDragEnd(DragEndEvent event) throws VetoDragException {
Widget node = (Widget) event.getSource();
int left = event.getContext().desiredDraggableX;
int top = event.getContext().desiredDraggableY;
AbsolutePanel panel = (AbsolutePanel) dropController.getDropTarget();
createConnector((Label) node, panel, left, top);
throw new VetoDragException();
}
});
}
}
protected UIObjectConnector createConnector(Label proxy, AbsolutePanel panel, int left, int top) {
Widget w;
String str = proxy.getText();
if(str.equals("START") || str.equals("STOP")){
w = new Label(proxy.getText()){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
w.getElement().setClassName("dnd-start-stop");
}
else{
w = new ListBox(){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
if(str.equals("ACTIVITY")){
getAItems((ListBox)w);
//w.getElement().addClassName("dnd-activity");
}
else if(str.equals("PROCESS")){
getPItems((ListBox)w);
//w.getElement().addClassName("dnd-process");
}
}
onCanvas.add(w);
left -= panel.getAbsoluteLeft();
top -= panel.getAbsoluteTop();
//panel.add(w,10,10);
panel.add(w, left, top);
dragController.makeDraggable(w);
return UIObjectConnector.wrap(w);
}
private void getAItems(ListBox w) {
for(int i=0;i<aItems.length;i++)
w.addItem(aItems[i].getActivityName());
}
private void getPItems(ListBox w) {
/*for(int i=0;i<pItems.length;i++)
w.addItem(pItems[i].getProcessName());*/
w.addItem("Process1");
}
protected void select(Widget w){
if(selected.isEmpty()) {
selected.add(w);
w.getElement().addClassName("color-green");
} else if(selected.contains(w)){
selected.remove(w);
w.getElement().removeClassName("color-green");
} else if(selected.size() == 1) {
Widget w2 = (Widget) selected.get(0);
connect(UIObjectConnector.getWrapper(w2), UIObjectConnector.getWrapper(w));
selected.clear();
}
}
protected void connect(Connector a, Connector b) {
//System.out.println(a.getLeft());
//System.out.println(b.getLeft());
add(new StraightTwoEndedConnection(a,b));
}
private void add(StraightTwoEndedConnection c) {
canvas.add(c);
connections.add(c);
c.update();
}
protected void remove(Connection c) {
connections.remove(c);
}
class MyHandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
Button name = (Button) event.getSource();
if(name.equals(stopDrag)){
if(name.getText().equals("Done Dragging")){
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeNotDraggable(w);
}
name.setText("Continue");
}
else {
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeDraggable(w);
}
name.setText("Done Dragging");
}
}
else{
}
}
}
}
I know this is quite old, but I was having similar issues with the gwt-connector library.
The connectors will not appear in the correct placement if you are using standards mode. Use quirks mode instead.
Additionally, you need to manually perform a connector.update() while your dnd components are being dragged (in your drag listener) for the connection to move with the endpoint while you are dragging.