Drag and Drop vbox element with show snapshot in javafx - drag-and-drop

I want drag an element in vbox as a parent and show node moving during drag and drop of element, how can do this with The slightest change.

Just register mouse listeners with the elements of the VBox. You want to call startFullDrag() on the node on a dragDetected event, and rotate the child nodes of the VBox on a dragReleased event. You can use the dragEntered and dragExited events if you want to give visual hints to the user about the drag.
See the API docs for more.
Simple example (code is way cleaner in JavaFX 8, btw):
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
final VBox root = new VBox(5);
final ScrollPane scroller = new ScrollPane();
scroller.setContent(root);
final Scene scene = new Scene(scroller,400,200);
for (int i=1; i<=20; i++) {
final Label label = new Label("Item "+i);
addWithDragging(root, label);
}
// in case user drops node in blank space in root:
root.setOnMouseDragReleased(new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
int indexOfDraggingNode = root.getChildren().indexOf(event.getGestureSource());
rotateNodes(root, indexOfDraggingNode, root.getChildren().size()-1);
}
});
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
private void addWithDragging(final VBox root, final Label label) {
label.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
label.startFullDrag();
}
});
// next two handlers just an idea how to show the drop target visually:
label.setOnMouseDragEntered(new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
label.setStyle("-fx-background-color: #ffffa0;");
}
});
label.setOnMouseDragExited(new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
label.setStyle("");
}
});
label.setOnMouseDragReleased(new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
label.setStyle("");
int indexOfDraggingNode = root.getChildren().indexOf(event.getGestureSource());
int indexOfDropTarget = root.getChildren().indexOf(label);
rotateNodes(root, indexOfDraggingNode, indexOfDropTarget);
event.consume();
}
});
root.getChildren().add(label);
}
private void rotateNodes(final VBox root, final int indexOfDraggingNode,
final int indexOfDropTarget) {
if (indexOfDraggingNode >= 0 && indexOfDropTarget >= 0) {
final Node node = root.getChildren().remove(indexOfDraggingNode);
root.getChildren().add(indexOfDropTarget, node);
}
}
public static void main(String[] args) {
launch(args);
}
}

This is an addendum to #James_D's excellent answer
This shows how to add an image preview to the draggable node as #James_D suggests in his comment:
private void addPreview(final VBox root, final Label label) {
ImageView imageView = new ImageView(label.snapshot(null, null));
imageView.setManaged(false);
imageView.setMouseTransparent(true);
root.getChildren().add(imageView);
root.setUserData(imageView);
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
imageView.relocate(event.getX(), event.getY());
}
});
}
private void removePreview(final VBox root) {
root.setOnMouseDragged(null);
root.getChildren().remove(root.getUserData());
root.setUserData(null);
}
Call addPreview() in label.setOnDragDetected(). Call removePreview() in label.setOnMouseDragReleased() and root.setOnMouseDragReleased().

There is a much better solution that is far cleaner now.
// Root is the node you want to drag, not the scene root.
root.setOnDragDetected(mouseEvent -> {
final ImageView preview = new ImageView(root.snapshot(null, null));
final Dragboard db = root.startDragAndDrop(TransferMode.ANY);
db.setContent( // Set your content to something here.
);
db.setDragView(preview.getImage());
mouseEvent.consume();
});

Related

How to fire event when scrolling up,javafx

I am developing chat application on java and i want to use function used by facebook to retrieve chat history when user scroll up. I tried "on Scroll" action which fire event whenever scroll reach top or down of scroll bar. Now i want to Fire action event only when scroll bar reach top like in facbook chat box.
Assuming that you have a ScrollPane, you can observe vvalueProperty of it:
scrollPane.vvalueProperty().addListener(
(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
if(newValue.doubleValue() == 0){
System.out.println( "AT TOP" );
// load more items
}
});
and you may also scroll to bottom with
scrollPane.setVvalue( scrollPane.getVmax() );
initially.
Here is the example of what you want. I hope this will help you.
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ScrollUtil extends Application
{
private boolean scrollToBottom = false;
private boolean scrollToTop = false;
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(final Stage stage) throws Exception
{
final VBox root = new VBox();
final ScrollPane scrollPane = new ScrollPane();
final VBox vBox = new VBox();
vBox.setAlignment(Pos.BOTTOM_CENTER);
scrollPane.setContent(vBox);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
Button button = new Button("add");
Button button3 = new Button("scroll up");
button3.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent actionEvent)
{
scrollToTop = true;
scrollPane.setVvalue(scrollPane.getVmin());
System.out.println("vmin= "+scrollPane.getVmin() + "; vmax = " + scrollPane.getVmax() + "; vvalue" + scrollPane.getVvalue());
}
});
button.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent actionEvent)
{
vBox.getChildren().add(new Label("hallo"));
scrollToBottom = true;
//System.out.println(scrollPane.getVmin() + "; max = " + scrollPane.getVmax() + "; " + scrollPane.getVvalue());
}
});
scrollPane.setVvalue(scrollPane.getVmax());
scrollPane.vvalueProperty().addListener(new ChangeListener<Number>()
{
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue)
{
if(scrollToBottom)
{
scrollPane.setVvalue(scrollPane.getVmax());
scrollToBottom = false;
}
if(newValue.doubleValue() ==0)
{
vBox.getChildren().add(new Label("hallo"));
System.out.println("min value ="+scrollPane.getVmin());
//scrollPane.setVvalue(scrollPane.getVmin());
scrollToTop = true;
System.out.println("now get the chat history");
}
}
});
Button button2 = new Button("scroll");
button2.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent actionEvent)
{
scrollPane.setVvalue(Double.MAX_VALUE);
}
});
root.getChildren().addAll(scrollPane, button, button2, button3);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}

Android ImageButton Onclick not working

I'm trying to change images when an image button is clicked. Even without the code for changing image my application is crashing whenever I use an onClickListener or try to set an onClick listener. How do i fix this I'm running app on kitkat api 19
package com.example.t11;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Scene extends ActionBarActivity {
ImageView scene=(ImageView) findViewById(R.id.images);
int i=0;
int[] imgarray = {R.drawable.i1,R.drawable.i2,R.drawable.i4,R.drawable.i6,R.drawable.i7,R.drawable.i8,R.drawable.i9,R.drawable.i10,R.drawable.i12};
//Just set one Click listener for the image
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scene);
Intent sceneint = getIntent();
ImageButton left = (ImageButton) findViewById(R.id.left);
ImageButton right= (ImageButton) findViewById(R.id.right);
// Left and right button listener creation
left.setOnClickListener(leftlistener);
right.setOnClickListener(rightlistener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.scene, menu);
return true;
}
View.OnClickListener rightlistener = new OnClickListener() {
public void onClick(View v1) {
//Increase Counter to move to next Image
i++;
scene.setImageResource(imgarray[i]);
}
};
View.OnClickListener leftlistener = new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instantiate the listener as an anonymous function :
left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
});
if you want the reference of the listener as well for some reason then try instantiating and assigning the listener before registering it with the button.

My Custom CursorAdapter doesn't update my ListView

I'm having troubles with my Custom CursorAdapter and my ListView, the fact is, I can save data in my sqlite Database in my custom ContentProvider but my ListView is not populated.
I know DB Operations are heavy long operations, therefore I do it in another thread and furthermore CursorLoader is a subclass of AsyncTaskLoader, so it should be prepared for that.
With SimpleCursorAdapter works fine but with this Custom CursorAdapter not.
Can anyone tell me what is wrong and how could I solve it?
Thanks in advance.
My code is the following
public class TextNoteAdapter extends CursorAdapter {
/*********** Declare Used Variables *********/
private Cursor mCursor;
private Context mContext;
private static LayoutInflater mInflater=null;
/************* TextNoteAdapter Constructor *****************/
public TextNoteAdapter (Context context, Cursor cursor, int flags) {
super(context, cursor,flags);
mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
mCursor = cursor;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = mInflater.inflate(R.layout.textnote_info, parent, false);
ViewHolder holder = new ViewHolder();
holder.note_name = (TextView)view.findViewById(R.id.note_name);
holder.creation_date = (TextView)view.findViewById(R.id.creation_date);
holder.modification_date = (TextView)view.findViewById(R.id.modification_date);
holder.label_creation_date = (TextView)view.findViewById(R.id.label_creation_date);
holder.label_modification_date = (TextView)view.findViewById(R.id.label_modification_date);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data what means, take the data from the cursor and put it in views
View vi = view;
ViewHolder holder = (ViewHolder)view.getTag();
if(view==null){
/****** Inflate textnote_info.xml file for each row ( Defined below ) *******/
vi = mInflater.inflate(R.layout.textnote_info, null);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
} else
holder=(ViewHolder)vi.getTag();
/************ Set Model values in Holder elements ***********/
holder.note_name.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_NOTE_NAME)));
holder.creation_date.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_CREATION_DATE)));
holder.modification_date.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_MODIFICATION_DATE)));
holder.label_creation_date.setText(Constants.LABEL_CREATION_DATE);
holder.label_modification_date.setText(Constants.LABEL_MODIFICATION_DATE);
}
#Override
protected void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
notifyDataSetChanged();
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView note_name;
public TextView creation_date;
public TextView modification_date;
public TextView label_creation_date;
public TextView label_modification_date;
}
}
And here my MainActivity
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>{
private Cursor cursor;
private Button addButton;
private ListView listView;
private TextNoteAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayListView();
addButton = (Button)findViewById(R.id.add_textnote);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starts a new Intent to add a Note
Intent intent = new Intent(getBaseContext(), TextNoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "add");
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
Log.i("TAG", "MainActivity:: onResume");
/** Starts a new or restarts an existing Loader in this manager **/
getLoaderManager().restartLoader(0, null, this);
}
private void displayListView() {
// That ensures a loader is initialized and active.
// If the loader specified by the ID already exists, the last created loader is reused.
// else initLoader() triggers the LoaderManager.LoaderCallbacks method onCreateLoader().
// This is where you implement the code to instantiate and return a new loader
getLoaderManager().initLoader(0, null, this);
// We get ListView from Layout and initialize
listView = (ListView) findViewById(R.id.textnote_list);
// DB takes long, therefore this operation should take place in a new thread!
new Handler().post(new Runnable() {
#Override
public void run() {
dataAdapter = new TextNoteAdapter(MainActivity.this, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(dataAdapter);
Log.i("TAG", "MainActivity:: Handler... Run()");
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
/** Get the cursor, positioned to the corresponding row in the result set **/
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// display the selected note
String noteName = cursor.getString(cursor.getColumnIndexOrThrow(TextNotesDb.KEY_NOTE_NAME));
Toast.makeText(getApplicationContext(), noteName, Toast.LENGTH_SHORT).show();
String rowId = cursor.getString(cursor.getColumnIndexOrThrow(TextNotesDb.KEY_ROWID));
// starts a new Intent to update/delete a Textnote
// pass in row Id to create the Content URI for a single row
Intent intent = new Intent(getBaseContext(), TextNoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "update");
bundle.putString("rowId", rowId);
intent.putExtras(bundle);
startActivityForResult(intent, 1);
}
});
}
/** This is called when a new Loader needs to be created.**/
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.i("TAG", "MainActivity:: onCreateLoader");
String[] projection = {
TextNotesDb.KEY_ROWID,
TextNotesDb.KEY_GUID,
TextNotesDb.KEY_NOTE_NAME,
TextNotesDb.KEY_NOTE,
TextNotesDb.KEY_CREATION_DATE,
TextNotesDb.KEY_MODIFICATION_DATE
};
CursorLoader cursorLoader = new CursorLoader(this, MyContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
dataAdapter.swapCursor(null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
As in comment below my Question, I could solve it by adding 2 lines. Now it should look like this
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.notifyDataSetChanged(); // <-
listView.setAdapter(dataAdapter); // <-
dataAdapter.swapCursor(data);
}

How to firing Zoomevent in Javafx 8

I'm working on a very simple program. I have an ImageView and I want to firing to this ImageView a ZoomEvent that I created. In Javafx 8 there 2 constructor that I can use to create ZoomEvent. But the listeners doesn't catch the event.
StackPane root = new StackPane();
final ImageView img = new ImageView(url);
img.setOnZoom(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom!");
}
});
img.setOnZoomStarted(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom Started!");
}
});
img.setOnZoomFinished(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom finished!");
}
});
ZoomEvent evt = new ZoomEvent(ZoomEvent.ANY, 200,200,200,200,false,false,false,false,false, false, 5.0,5.0, null);
root.getChildren().add(img);
Scene scene = new Scene(root, 600, 600);
primaryStage.setTitle("Zoom Sample");
primaryStage.setScene(scene);
primaryStage.show();
This is my code so far and I can't figure out what is wrong. There isn't any output.
You never fired the event with ZoomEvent.fireEvent(target, event) or stage.fireEvent(event).
You created the wrong type of event (create a ZoomEvent.ZOOM, not a ZoomEvent.ANY).
You didn't set the event screen co-ordinates correctly.
Working sample:
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.input.ZoomEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Zoom extends Application {
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage stage) {
final ImageView img = new ImageView(
"http://icons.iconarchive.com/icons/kirei-kaze/kikis-delivery-service/256/jiji-icon.png" // image license: License: Free for non-commercial use. The products or characters depicted in these icons are © by Studio Ghibli. Linkback: http://www.iconarchive.com/artist/kirei-kaze.html
);
img.setOnZoom(e -> System.out.println("Zoom!"));
StackPane layout = new StackPane(img);
stage.setScene(new Scene(layout, 600, 600));
stage.show();
Point2D screenCoords = layout.localToScreen(300, 300);
ZoomEvent evt = new ZoomEvent(
ZoomEvent.ZOOM,
300, 300,
screenCoords.getX(), screenCoords.getY(),
false,false,false,false,false, false, 5.0,5.0, null
);
ZoomEvent.fireEvent(img, evt);
}
}

How to register ClickHandler to a vector grahpic in gwt-graphics and get-plattform

I’m trying to use gwt-graphics in a gwt-plattform project.
When I try to register a ClickHandler of a circle I got an exception:
I can add a ClickHandler to the circle in the view, but how can a add in the presenter?
view:
import org.vaadin.gwtgraphics.client.DrawingArea;
import org.vaadin.gwtgraphics.client.shape.Circle;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
public class MainPageView extends ViewImpl implements MainPagePresenter.MyView {
private static String html = "<h1>Web Application Starter Project</h1>\n"
+ "<table align=\"center\">\n"
+ " <tr>\n"
+ " <td colspan=\"2\" style=\"font-weight:bold;\">Please enter your name:</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td id=\"nameFieldContainer\"></td>\n"
+ " <td id=\"sendButtonContainer\"></td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td colspan=\"2\" style=\"color:red;\" id=\"errorLabelContainer\"></td>\n"
+ " </tr>\n" + "</table>\n";
private final HTMLPanel panel = new HTMLPanel(html);
private final Label errorLabel;
private final TextBox nameField;
private final Button sendButton;
private AbsolutePanel absolutePanel = new AbsolutePanel();
Image image_1;
Image image;
DrawingArea d;
Circle circle;
#Inject
public MainPageView() {
sendButton = new Button("Send");
nameField = new TextBox();
nameField.setText("GWT User");
errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
panel.add(nameField, "nameFieldContainer");
panel.add(sendButton, "sendButtonContainer");
d = new DrawingArea(500, 500);
panel.add(absolutePanel);
absolutePanel.setHeight("500px");
// circle.addClickHandler(new ClickHandler() {
//
// #Override
// public void onClick(ClickEvent event) {
// Window.alert("image2");
//
// }
// });
image = new Image("ball1.png");
absolutePanel.add(image, 59, 10);
image.setSize("100px", "100px");
image_1 = new Image("Hexagon.svg");
absolutePanel.add(image_1, 115, 10);
image_1.setSize("100px", "100px");
absolutePanel.add(d, 100, 100);
//
Circle circle = new Circle(100, 100, 150);
circle.setStrokeColor("red");
d.add(circle);
panel.add(errorLabel, "errorLabelContainer");
}
#Override
public Widget asWidget() {
return panel;
}
#Override
public HasValue<String> getNameValue() {
return nameField;
}
#Override
public HasClickHandlers getSendClickHandlers() {
return sendButton;
}
#Override
public void resetAndFocus() {
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
}
#Override
public void setError(String errorText) {
errorLabel.setText(errorText);
}
// #Override
// public HasClickHandlers getImage1() {
// return image;
// }
//
// #Override
// public HasClickHandlers getImage2() {
// return image_1;
//
// }
#Override
public HasClickHandlers getCircle() {
return circle;
}
}
Presenter:
package mybla.client.core;
import org.vaadin.gwtgraphics.client.shape.Circle;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.annotations.NameToken;
import mybla.client.place.NameTokens;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.google.inject.Inject;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasValue;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import mybla.shared.FieldVerifier;
public class MainPagePresenter extends
Presenter<MainPagePresenter.MyView, MainPagePresenter.MyProxy> {
public interface MyView extends View {
HasValue<String> getNameValue();
HasClickHandlers getSendClickHandlers();
void resetAndFocus();
void setError(String errorText);
HasClickHandlers getCircle();
// HasClickHandlers getImage2();
//
// HasClickHandlers getImage1();
}
#ProxyStandard
#NameToken(NameTokens.main)
public interface MyProxy extends ProxyPlace<MainPagePresenter> {
}
private final PlaceManager placeManager;
#Inject
public MainPagePresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy, final PlaceManager placeManager) {
super(eventBus, view, proxy);
this.placeManager = placeManager;
}
#Override
protected void revealInParent() {
RevealRootContentEvent.fire(this, this);
}
#Override
protected void onBind() {
super.onBind();
registerHandler(getView().getSendClickHandlers().addClickHandler(
new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
sendNameToServer();
}
}));
// registerHandler(getView().getImage1().addClickHandler(new ClickHandler() {
//
// #Override
// public void onClick(ClickEvent event) {
// Window.alert("image1");
//
// }
// }));
registerHandler(getView().getCircle().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("image2");
}
}));
}
#Override
protected void onReset() {
super.onReset();
getView().resetAndFocus();
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
getView().setError("");
String textToServer = getView().getNameValue().getValue();
if (!FieldVerifier.isValidName(textToServer)) {
getView().setError("Please enter at least four characters");
return;
}
// Then, we transmit it to the ResponsePresenter, which will do the server call
placeManager.revealPlace(new PlaceRequest(NameTokens.response).with(
ResponsePresenter.textToServerParam, textToServer));
}
}
In your presenter:
getView().getCircle().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event)
{
Window.alert("image2");
}
});
This will use the getter method set in the presenter.view, to access the circle in the View itself.
Looks like the circle you instantiate in your View's constructor is a local variable, not the class-scope variable your getCircle() method returns. Additionally, the commented out code for adding the onclick handler is before the code that instantiates the local variable.
You have:
...
// circle.addClickHandler(new ClickHandler() {
//
// #Override
// public void onClick(ClickEvent event) {
// Window.alert("image2");
// }
// });
...
Circle circle = new Circle(100, 100, 150);
circle.setStrokeColor("red");
d.add(circle);
Change it to:
...
circle = new Circle(100, 100, 150); // This now references the class-scope variable, rather than creating a new local variable.
circle.setStrokeColor("red");
d.add(circle);
circle.addClickHandler(new ClickHandler() { // This will no longer throw a null-pointer exception.
#Override
public void onClick(ClickEvent event) {
Window.alert("image2");
}
});