GWT Canvas2D draw Image - gwt

/**
* This is the entry point method.
*/
public void onModuleLoad() {
Canvas canvas = Canvas.createIfSupported();
final Context2d context2d = canvas.getContext2d();
RootPanel.get("canvas").add(canvas);
Image img = new Image("face.png");
final ImageElement face = ImageElement.as(img.getElement());
img.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
context2d.drawImage(face, 0, 0);
}
});
//RootPanel.get("canvas").add(img);
}
This is my code. I want to draw the image onto the canvas.
This works if the last line:
RootPanel.get("canvas").add(img);
is NOT commented out.
But with the line commented it seems that the image wont be loaded or so. Any ideas?

The Image widget has to be added to the page to trigger image load. Just make it invisible:
public void onModuleLoad() {
Canvas canvas = Canvas.createIfSupported();
final Context2d context2d = canvas.getContext2d();
RootPanel.get().add(canvas);
Image img = new Image("face.png");
final ImageElement face = ImageElement.as(img.getElement());
img.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
context2d.drawImage(face, 0, 0);
}
});
img.setVisible(false);
RootPanel.get().add(img);
}

Have you placed the image within the WEB-INF folder? That's where GWT loads the images from. Normally it's recommend to create an "images" folder so you can load it with "images/face.png".

You can use an image loader, such as: http://code.google.com/p/google-web-toolkit-incubator/wiki/ImageLoader.

If you want to avoid needing to add the image to the page to load (which can cause the image to flash up on the page), you can use a native JavaScript load.
package com.mypackage;
public interface Loaded<T> {
public void data(T data);
}
public static native void loadImageNative(String imgBase64, Loaded<ImageElement> loaded) /*-{
var image = new Image();
image.onload = function() {
loaded.#com.mypackage.Loaded::data(*)(image);
};
image.src = imgBase64;
}-*/;
public void onModuleLoad() {
Canvas canvas = Canvas.createIfSupported();
Context2d context2d = canvas.getContext2d();
String base64Img = MyResouces.myImage().getSafeUri().asString();
RootPanel.get().add(canvas);
loadImageNative(base64Img, imageLoaded -> {
context2d.drawImage(imageLoaded, 0, 0);
});
}

Related

SimplePanel can only contain one child widget

When i run the following Code and push Button "Push", more than once a time, i get browser error "simplePanel can only contain one child widget". How can i solve that problem? thank you in advance! Jogi
public class Projekt implements EntryPoint {
private RootPanel rootPanel;
public void onModuleLoad() {
rootPanel = RootPanel.get("gwtContainer");
rootPanel.setSize("1902", "868");
final AbsolutePanel boundaryPanel = new AbsolutePanel();
boundaryPanel.setStyleName("frame1");
boundaryPanel.setSize("1455px", "600px");
final Diagram diagram = new Diagram(boundaryPanel);
RootPanel.get().add(boundaryPanel, 446, 242);
final Connector con = new Connector(100, 300, 300, 500);
Button la = new Button("Push");
la.setSize("200", "200");
RootPanel.get().add(la);
Button la2 = new Button("Push2");
la2.setSize("200", "200");
RootPanel.get().add(la2);
final Image img = new Image("images/concrete.svg");
img.setSize("200", "200");
final Shape shapei = new Shape(img);
Image img2 = new Image("images/variable.svg");
img2.setSize("200", "200");
boundaryPanel.add(img2, 200,200);
final Shape shapei2 = new Shape(img2);
shapei2.showOnDiagram(diagram);
la.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
boundaryPanel.add(img, 100,100);
shapei.showOnDiagram(diagram);
}
});
la2.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
con.showOnDiagram(diagram);
}
});
diagram.addDiagramListener(new DiagramListenerAdapter() {
#Override
public void onElementConnect(ElementConnectEvent event) {
if (con.startEndPoint.isGluedToConnectionPoint()) {
Widget connected = con.startEndPoint.gluedConnectionPoint.parentWidget;
if(connected.equals(shapei.connectedWidget)){
Image logo = new Image("images/xor.svg");
logo.setSize("100", "100");
boundaryPanel.add(logo);
}
else if(connected.equals(shapei2.connectedWidget)){
Image logo2 = new Image("images/and.svg");
logo2.setSize("100", "100");
boundaryPanel.add(logo2);
};
}}
});
}}
RootPanel.get() is a SimplePanel. You try to add more than one child to it, resulting in this error.
Instead, you should add HTMLPanel, for example, to your RootPanel, and then add all the children to this HTMLPanel.
I suppose your Diagram extends GWT's SimplePanel
class? SimplePanel can contain only a single widget, have a look here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SimplePanel.html
You could either extend a different class, or call the remove(Widget w) method to remove the existing widget before trying to add a new one.

displaying jpg to a jPanel

So i am trying to add an image to my program after a button is pressed with a certain value entered into a text field. I want the image to be blank until the button is pressed with the correct value. The only issue i seem to be having is making the photo appear, i know the output should be working. here is the code i have for adding the label.
photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");
here is the code for when the value is entered correctly
if (error) {
photo.setIcon(image);
}
now im still pretty new at this so go easy on me.
Here is simple example for you:
public class Frame extends JFrame {
private JLabel label;
public Frame() {
getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
JButton b = new JButton("show Icon");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
URL resource = getClass().getResource("/res/3_disc.png");
ImageIcon ico = new ImageIcon(resource);
label.setIcon(ico);
}
});
getContentPane().add(b,BorderLayout.NORTH);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
"/res/3_disc.png" - is my icon which is placed in my project in res folder.

CheckBox clickhandler code doesn't work...there is no compile time error...look at the snap shot

CheckBox clickhandler code doesn't work...there is no compile time error...look at the snap shotlook at the snap shot in which there is no image in popup...i have highlighted it
cb1.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
System.out.println("hello2");
boolean checked = ((CheckBox) event.getSource()).getValue();
if (checked) {
System.out.println("hello3");
int left = toothWidget.getToothImage().getAbsoluteLeft();
int top = toothWidget.getVPanel().getAbsoluteTop();//toothWidget.getToothImage().getAbsoluteTop();
Image im = new Image();
im.setUrl(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
System.out.println(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
int offx = left;
int offy = top;
final PopupPanel popup1 = new PopupPanel(true);
popup1.setStylePrimaryName("transparent");
popup1.setPopupPosition(Math.max(offx, 0),Math.max(offy, 0));
//popup.add(im);
ToothWidget wgt = new ToothWidget(toothWidget.getToothNumber(),menuItem.getImg(), toothWidget.getTeeth());
toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).put(menuItem.getName(), wgt);
wgt.setMenu(toothWidget.getMenu());
wgt.setPanel(popup1);
popup1.add(wgt);
popup1.show();
}
else{
ToothWidget wgt = toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).remove(menuItem.getName());
wgt.getPanel().hide();
}
}
});
WEB Dev 101 - Always use FireFox/FireBug's Network/Image console to check for URL mismatch . You will be seeing 404 errors for the Image path.
Where is YOUR Image located?
1) public folder parallel to your gwt.xml
If you have images folder in your gwt module's public folder you need to use im.setUrl(GWT.getModuleBaseURL()+"/images/"+menuItem.getImg());
or
2) webapps folder
If you have images in deployed into your war/images you need to use
im.setUrl(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
If the above does not solve the issue then you may not have the image at all under "images"
try this. It is better to use the ValueChangeHandler that works for sure and is used for changing values.
CheckBox cb1 = new CheckBox();
cb1.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
#Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
Boolean isChecked = event.getValue();
if (isChecked) {
System.out.println("hello3");
int left = toothWidget.getToothImage().getAbsoluteLeft();
int top = toothWidget.getVPanel().getAbsoluteTop();//toothWidget.getToothImage().getAbsoluteTop();
Image im = new Image();
im.setUrl(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
System.out.println(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
int offx = left;
int offy = top;
final PopupPanel popup1 = new PopupPanel(true);
popup1.setStylePrimaryName("transparent");
popup1.setPopupPosition(Math.max(offx, 0),Math.max(offy, 0));
//popup.add(im);
ToothWidget wgt = new ToothWidget(toothWidget.getToothNumber(),menuItem.getImg(), toothWidget.getTeeth());
toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).put(menuItem.getName(), wgt);
wgt.setMenu(toothWidget.getMenu());
wgt.setPanel(popup1);
popup1.add(wgt);
popup1.show();
}
else
{
ToothWidget wgt = toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).remove(menuItem.getName());
wgt.getPanel().hide();
}
}
});
}
Plus the images/ folder must be inside the war forlder (though i think you already know that having developed this site)
Also check what menuItem.getImg() returns. It might return only the filename but not the extension or something else entirely.

CheckBox Code Doesn't working there is no compile time error

public SubMenuItemCommand(MenuObject menuItem,JsArray listOfMenu,ToothWidget toothWidget){ this.menuItem=menuItem; this.listOfMenu=listOfMenu; this.toothWidget=toothWidget; }
cb1.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
System.out.println(menuItem.getImage());
boolean checked = ((CheckBox) event.getSource()).getValue();
if (checked) {
System.out.println("hello3");
int left = toothWidget.getToothImage().getAbsoluteLeft();
int top = toothWidget.getVPanel().getAbsoluteTop();//toothWidget.getToothImage().getAbsoluteTop();
Image im = new Image();
im.setUrl("images/"+menuItem.getImg());
int offx = left;
int offy = top;
final PopupPanel popup1 = new PopupPanel(true);
popup1.setStylePrimaryName("transparent");
popup1.setPopupPosition(Math.max(offx, 0),Math.max(offy, 0));
//popup.add(im);
ToothWidget wgt = new ToothWidget(toothWidget.getToothNumber(),menuItem.getImg(), toothWidget.getTeeth());
toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).put(menuItem.getName(), wgt);
wgt.setMenu(toothWidget.getMenu());
wgt.setPanel(popup1);
popup1.add(wgt);
popup1.show();
}
else{
ToothWidget wgt = toothWidget.getTeeth().getMap().get(toothWidget.getToothNumber()).remove(menuItem.getName());
wgt.getPanel().hide();
}
}
});
Usually it is a path issue. i.e image location is not what you are setting up.
If you have images folder in your gwt module's public folder you need to use im.setUrl(GWT.getModuleBaseURL()+"/images/"+menuItem.getImg());
If you have images in your war/images you need to use
im.setUrl(GWT.getHostPageBaseURL()+"/images/"+menuItem.getImg());
Also you can always use FireFox/FireBug's Network/Image console to check which URL is being accessed.

GWT client side cropping

I'm stuck on integrating gwt with JCrop or imgareaselect javascript libraries
I have an image, which url is changing each time the client change the file choosen from its filesystem (using an upload widget).
I want the user select the area in its image, this way i will be able to have images with aspect ratio respected respect to the client wishes.
Problem is i can't succed in making imgareaselect or jcrop called on load event, each time i have null, if i try jquery ("imagepreview") jquery is unknow at execution time, if i try some $("#imagepreview") i get a $ is undefined...
PLEASE any help...
Regards.
public class ThisWidget extends LayoutContainer {
public void onRender(Element parent, int index) {
super.onRender(parent, index);
setLayout(new VBoxLayout());
setWidth("100%");
final FormPanel uploadPhotoPanel = new FormPanel();
uploadPhotoPanel.setWidth("100%");
uploadPhotoPanel.setHeight("150px");
Label label = new Label("Ajouter une photo");
add(label);
uploadPhotoPanel.setAction(GWT.getModuleBaseURL()
+ "photoload/uploadpreview.ctz");
uploadPhotoPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadPhotoPanel.setMethod(FormPanel.METHOD_POST);
final FileUploadField file = new FileUploadField();
file.setName("FILE");
uploadPhotoPanel.add(file);
file.addHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
uploadPhotoPanel.submit();
}
}, ChangeEvent.getType());
final Button btn = new Button("Ajouter",
new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
uploadPhotoPanel.submit();
}
});
final Image previewimage;
previewimage = new Image();
DOM.setElementAttribute(previewimage.getElement(), "id",
"previewimage");
previewimage.setSize("200px", "200px");
previewimage.addLoadHandler(new LoadHandler(){
protected native void onPreviewLoad() /*-{
document.getElementById("previewimage").imgAreaSelect({
aspectRatio : '1:1',
handles : true,
fadeSpeed : 200
});
}-*/;
#Override
public void onLoad(LoadEvent event) {
onPreviewLoad();
}});
uploadPhotoPanel
.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
previewimage.setUrl(GWT.getModuleBaseURL()
+ "photoload/downloadpreview.ctz?tsp="
+ System.currentTimeMillis());
}
});
add(uploadPhotoPanel);
add(previewimage);
add(btn);
}
Use $wnd.$("#imagepreview") or $wnd.jquery("#imagepreview").
(Updated to fix the forgotten #)