Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable / change style of wicket button link in onClick()

Tags:

java

wicket

In a Wicket app, I have a bunch of <button> elements to which I'm attacking a Link component. Now in the onClick() method of the component I want to disable or change the style of the button. How can I do that? Calling setEnabled(false) has no effect.

like image 987
Michael Borgwardt Avatar asked Dec 10 '22 08:12

Michael Borgwardt


2 Answers

Repeated uses of onClick() are operating on the same object in memory. If you're not using Ajax, you can still maintain some state in an anonymous subclass of Link. Then, you can use onBeforeRender() and onComponentTag() to change how it is displayed each time.

Link<Void> link = new Link<Void>("myLink") {

    private String customCSS = null;
    private boolean customEnabled = true;

    public void onClick() {
        if (/* test to determine disabled */) {
            customCSS = "disabled";
            customEnabled = false;
        } else {
            customCSS = null;
            customEnabled = true;
        }
    }

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);
        if (customCSS != null)
            tag.put("class", customCSS);
    }

    @Override
    public boolean isEnabled() {
        return super.isEnabled() && customEnabled;
    }
};

AttributeModifiers (or other behaviors) aren't good for this case because, if you add them in the onClick() method, they will begin stacking on the same link for each click - since they are maintained as part of the Link's state.

Your Link can keep track of all manner of state, allowing your onClick() method to enable/disable/change/etc with repeated clicks.

You can also override onBeforeRender(), isVisible(), and other methods that are run each time the link is displayed on the page. The constructor, onConfigure(), and others are run just once, regardless of how many times you click the button.

like image 144
jbrookover Avatar answered Dec 11 '22 22:12

jbrookover


I don't think this is an entirely good idea in Wicket. Of course it could be done by trickery, but it's far simpler to either:

  1. Override the isEnabled() method to return a value derived from the model of the form/component.
  2. Attach an AttributeModifier when you create the component, and use a model for it which returns a value derived as above.

Whichever you choose, the principle is to let Wicket "pull" rendering information in rather than pushing it explicitly.

like image 23
biziclop Avatar answered Dec 11 '22 23:12

biziclop