- To request focus for a component, we need to use a little JavaScript, we can do so using a behavior:
Code Block borderStyle solid public class FocusOnLoadBehavior extends AbstractBehavior { private Component component; public void bind( Component component ) { this.component = component; component.setOutputMarkupId(true); } public void renderHead( IHeaderResponse iHeaderResponse ) { super.renderHead(iHeaderResponse); iHeaderResponse.renderOnLoadJavascript("document.getElementById('" + component.getMarkupId() + "').focus()"); } public boolean isTemporary() { // remove the behavior after component has been rendered return true; } }
- Now, to use that behavior, all we have to do is:
Code Block borderStyle solid public class MyPage extends WebPage { public MyPage() { Form form = new Form("form"); TextField field1 = new TextField("field1"); field1.add(new FocusOnLoadBehavior()); form.add(field1); add(form); } }
- !!! Please, never focus a component in "onload" event. It's very annoying if page is not loaded yet but user already scrolling/editing controls and suddenly browser jumps him to some other control. More sensible put the focus() code just after component tag. I introduce other code, seems works for me:
Code Block borderStyle solid public class FocusOnLoadBehavior extends AbstractBehavior { @Override public void bind(Component component) { super.bind(component); component.setOutputMarkupId(true); component.setComponentBorder(new IComponentBorder() { public void renderBefore(Component component) { } public void renderAfter(Component component) { final Response response = component.getResponse(); response.write( "<script type=\"text/javascript\" language=\"javascript\">document.getElementById(\"" + component.getMarkupId() + "\").focus()</script>"); } }); } @Override public boolean isTemporary() { return true; } }