|
QuickTips
Quick Tips about how things work
AdvertisingTable of Contents
Quick TipsQuick tips that might help you. These are things that I have learned along the way that make my job easier. Console/Syslog DebuggingUsing System.out.println to print to debugger console or when running it on the server it will print to the /var/log/Syslog which is very helpful for debugging.
Print RPCs Serialized ResponseI found this in GWT sample Dynamic Table. I love this function b/c it prints out the object that will be sent in the RPC. Put this snippet in your server side of the rpc call, MyServerImpl.java class.
Serialization - Passing Data AroundI love this way of moving data around from client to server, server to client and between classes. This has got to be one of the coolest tricks. /**
* Hold relevant data for Bible. And pass it around.
* This class is meant to be serialized in RPC calls.
*/
public class BibleData implements IsSerializable {
//bible passage choices
public String[] StartBook;
public int StartChapter;
public int StartVerse;
public String[] EndBook;
public int EndChapter;
public int EndVerse;
//bible passage selections
public int rsID;
public int selStartBook;
public int selStartChapter;
public int selStartVerse;
public int selEndBook;
public int selEndChapter;
public int selEndVerse;
}ImageShow an external image on your page.//stick the image in the ~/www folder HorizontalPanel pLoading = new HorizontalPanel(); String sImage = GWT.getModuleBaseURL() + "loading2.gif"; Image image = new Image(sImage); pLoading.add(image); String ComparisonYou can compare strings like this. When using string, its best to always init with null, and then always check the string var before doing something with it.
ClicklistenerAvoid calling a listener more than once! Add the clicklistener in the constructor of the widget not a method called over and over. Every time you call a method with a clicklister, you add another observer to that object. Then if you want to do something with that object, you may cause multiples of something to happen, which is annoying!
Keyboardlistener
public class CalculatorWidget extends Composite implements ClickListener, KeyboardListener {
TextBox tbDisplay = new TextBox();
public CalculatorWidget() {
//listen to display
tbDisplay.addKeyboardListener(this);
RootPanel.get().add(tbDisplay);
}
public void onClick(Widget sender) {
}
public void onKeyDown(Widget sender, char keyCode, int modifiers) {
}
public void onKeyPress(Widget sender, char keyCode, int modifiers) {
RootPanel.get().add(new Label("key pressed: " + keyCode + " modifier: " + modifiers));
switch (keyCode) {
case KeyboardListener.KEY_ALT:
break;
case KeyboardListener.KEY_BACKSPACE:
break;
case KeyboardListener.KEY_CTRL:
break;
case KeyboardListener.KEY_DELETE:
break;
case KeyboardListener.KEY_DOWN:
break;
case KeyboardListener.KEY_END:
break;
case KeyboardListener.KEY_ENTER:
break;
case KeyboardListener.KEY_ESCAPE:
break;
case KeyboardListener.KEY_HOME:
break;
case KeyboardListener.KEY_LEFT:
break;
case KeyboardListener.KEY_PAGEDOWN:
break;
case KeyboardListener.KEY_PAGEUP:
break;
case KeyboardListener.KEY_RIGHT:
break;
case KeyboardListener.KEY_SHIFT:
break;
case KeyboardListener.KEY_TAB:
break;
case KeyboardListener.KEY_UP:
break;
default:
String keyPressed = Character.toString(keyCode);
if (keyPressed.equals("+") & (modifiers == 1) | keyPressed.equals("+")) { // +
} else if ((keyPressed.equals("8") & (modifiers == 1)) | keyPressed.equals("*")) { // *
} else if (keyPressed.equals("-")) { // -
} else if (keyPressed.equals("/")) { // /
} else if (Character.isDigit(keyCode)) { //0-9
} else if (keyPressed.equals("=")) { // =
} else { //all other characters
Window.alert("others");
}
break;
}//end case
}//end onKeyPress
public void onKeyUp(Widget sender, char keyCode, int modifiers) {
}
}Get ListBox Value's IndexHere is a method used to find the value's index, so then you can setSelected for listbox by value.
Get Listbox Selected Value (int)Get a listbox's selected value
Get Widget(s) Data In a PanelGetting Widgets in a panel is a nice way to interact with widgets you make. You can add several widgets into a panel, and get all of them by looping through the widgets in the panel. I make a specific panel to put all my reminder widgets in. Then I gather data and use it elsewhere.
Observe Events On Vertical PanelAdd this class and use it just like you would a vertical panel. This extends vertical panel and allows you to watch for events on the panel. This class below is only watching for clicks, but you can watch for all the events by adding them to sink events. public class WatchEventPanel extends VerticalPanel {
/**
* change listener to watch for fired events
*/
private ChangeListenerCollection changeListeners;
/**
* constructor - extending VerticalPanel with event watching
*/
public WatchEventPanel() {
//watch this widgets events
sinkEvents(Event.ONCLICK);
}
/**
* watch for particular browser events - sinkEvents(Events.[ONCLICK|etc])
*/
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
if (changeListeners != null) {
changeListeners.fireChange(this);
}
break;
}
}
/**
* add change listener - watch for changes in this widget
* @param listener
*/
public void addChangeListener(ChangeListener listener) {
if (changeListeners == null)
changeListeners = new ChangeListenerCollection();
changeListeners.add(listener);
}
/**
* remove change listener - remove watching for changes in this widget
* @param listener
*/
public void removeChangeListener(ChangeListener listener) {
if (changeListeners != null)
changeListeners.remove(listener);
}
}Another way to watch for events on a vertical panel using sinkEvents. In this class, I watch for Click using a changelistener. I observe mouse events using mouselistener. You can observe this verticalPanel widget via using the mouselistener and/or change listener. There are lots of different ways you can configure listeners. /**
* I use this panel for the drag handler for my composite widgets
* dragHandler = where the mouse holds the widget while dragging
*
* @author Brandon Donnelson
*
* I extend the vertical panel - not a composite widget
*/
public class WatchEventPanel extends VerticalPanel implements SourcesMouseEvents {
private MouseListenerCollection mouseListeners;
private ChangeListenerCollection changeListeners;
/**
* constructor - extending VerticalPanel with event watching
*/
public WatchEventPanel() {
//watch this widget's mouse events
sinkEvents(Event.MOUSEEVENTS);
}
/**
* watch for browser events - from sinkEvents([MouseEvents])
*/
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (mouseListeners != null) {
mouseListeners.fireMouseEvent(this, event);
}
if (changeListeners != null) {
changeListeners.fireChange(this);
}
break;
case Event.ONMOUSEMOVE:
if (mouseListeners != null) {
mouseListeners.fireMouseEvent(this, event);
}
break;
case Event.ONMOUSEOUT:
break;
case Event.ONMOUSEOVER:
break;
case Event.ONMOUSEUP:
if (mouseListeners != null) {
mouseListeners.fireMouseEvent(this, event);
}
break;
case Event.ONMOUSEWHEEL:
break;
}
}
/**
* observer stuff
*/
public void addMouseListener(MouseListener listener) {
if (mouseListeners == null)
mouseListeners = new MouseListenerCollection();
mouseListeners.add(listener);
}
public void removeMouseListener(MouseListener listener) {
if (mouseListeners != null)
mouseListeners.remove(listener);
}
/**
* add change listener - watch for changes in this widget
* @param listener
*/
public void addChangeListener(ChangeListener listener) {
if (changeListeners == null)
changeListeners = new ChangeListenerCollection();
changeListeners.add(listener);
}
/**
* remove change listener - remove watching for changes in this widget
* @param listener
*/
public void removeChangeListener(ChangeListener listener) {
if (changeListeners != null)
changeListeners.remove(listener);
}
}Parsing Query Stringget/pass parameters from the http query string. I use the history token to pass paramters, which makes more sense, since you don't have to refresh the page. Here is my method I do it with.
/**
* init history support, start watching for changes in history
*
* observe history changes (tokens)
*/
public void initHistorySupport() {
History.addHistoryListener(this);
// check to see if there are any tokens passed at startup via the
// browser’s URI
String token = History.getToken();
if (token.length() == 0) {
onHistoryChanged("trainer");
} else {
onHistoryChanged(token);
}
}
/**
* parse history token ?[var=1&var2=2&var3=3]
*
* Parse the history token like querystring - domain.tld#historyToken?params
*
* @param historyToken
* @return
*/
public static HashMap parseHistoryToken(String historyToken) {
//skip if there is no question mark
if (!historyToken.contains("?")) {
return null;
}
// ? position
int questionMarkIndex = historyToken.indexOf("?") + 1;
//get the sub string of parameters var=1&var2=2&var3=3...
String[] arStr = historyToken.substring(questionMarkIndex, historyToken.length()).split("&");
HashMap params = new HashMap();
for (int i = 0; i < arStr.length; i++) {
String[] substr = arStr[i].split("=");
params.put(substr[0], substr[1]);
//debug
System.out.println("param[" + i + "]=" + arStr[i]);
}
//debug
System.out.println("map: " + params);
return params;
}Google Analytics Track Anchor TagMoved to project_UrchinTracker - Extending this information there. Round PercentageRound a double. Round a percentage. Round a decimal to places. private double roundDouble(double d, int places) {
return Math.round(d * Math.pow(10, (double) places)) / Math.pow(10,
(double) places);
}
private double exampleUse() {
int count = 6;
int days = 21;
// calculate ratio
double ratio = 0;
if (count > 0) {
ratio = (double)count / (double)days ;
} else {
ratio = 0;
}
// round
ratio = roundDouble(ratio, 4);
// make it a percentage
ratio = ratio * 100;
return ratio;
}Slit String (CSV)Split a comma separated string with double quotes encasing them.
Remove HTML TagsStrip out html tags that could be dangerous. Remove html tags before drawing to screen. May need to do something like this if the request comes from rpc for safety.
TimerTimer example. Show something delayed or how then hide it.
Url EncodeEncode url. Use this both on the client and server side.
Servlet InformationGet servlet request GET/POST information. Get Requesting url, ip address, and other information that came in on the header request to the servlet.
Send a Widget To Popup WindowThis is what I do so i can print a widget. I send the widget.toString(); to popup window.
Get Browser TypeGet the type of browser using the application.
Including Another ProjectWhen including another project to your project. Things to remember.
PagingPaging widget. I use this when I want to page through a record set.
Paging Button
|
Sign in to add a comment





very useful stuff... thank you.