开发者

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
        开发者_如何学Cprotected void onSubmit(AjaxRequestTarget target, Form<?> form)
        { //how to change Button label here?
         }

}


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.


Additionally to biziclop's answer, here is a solution for text with changing parameter.

In your java code:

AjaxButton yourButton = new AjaxButton("btnId"){
//your button's implementation goes here
};
int yourVariable = 42;
Label yourLabel = new Label("labelId", new Model<String>() {
        public String getObject() {
            String text = MessageFormat.format(new Localizer().getString("IdForLocalizerInYourLocalizerFile", null), yourVariable);
            return text;
        }
    })
yourButton.add(yourLabel);

In your html:

  <a type="submit" wicket:id="btnId">
    <span wicket:id="labelId">[This text will never be seen, will be replaced by "The var..."]</span>
  </a>

Finally your localization file will contain a line like:

IdForLocalizerInYourLocalizerFile= The variable's value is {0}. It will be replaced whenever it changes and button component is added to target. Text will remain.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜