javaajaxbuttonwicketria

Wicket: Changing the text of an AjaxButton on submit


I'm a noob to Wicket and trying to change the text of a AjaxButton on submit. So the idea is that the for the first time the page loads, the user sees an AjaxButton labeled e.g. "1", after clicking the button, the label of the button changes to "2" and after the next click to "3" and so on...This can't be hard, but as I said, I'm a noobie when it comes to wicket. All help appreciated!

form.add(new AjaxButton("ajax-button", form)
    {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form)
        { //how to change Button label here?
         }

}


Solution

  • The answer is simple: use a model.

            //counter field declared in page class
            private int counter;
    
                ...
    
        form.add(new AjaxButton("ajax-button", new PropertyModel<String>(this,
                "counter", form)) {
    
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                counter++;
                target.addComponent(this);
    
            }
        });
    

    This is probably the most important rule of Wicket: when you need something changing, use a model. This takes some time getting used to, especially if you have experience with more "traditional" frameworks, and haven't used Swing either.

    N.b.: keeping the counter in your page class may not be a good idea, but the general idea is the same.