set tooltip for disabled button in gwt

In my recent project, I need to set tooltip for disabled button so that user can get the info why this button is disabled and what action to take in order to enable it.

As we know the disabled button or menu item in gwt does not sink event, so even if we use setTooltip for the widget, when user hover on it he could not see the tooltip because we can not catch the hover event.

 

Swallow the click event seems to be the easiest way.

I was thinking of remove the handler for the widget instead of swallow the event. It turns out to be more complicated

A quick workaround is to create a new widget that subclasses GWT/GXT’s button/menuItem, adding the following override:

 

package org.finra.cdip.cobra.issuelist.client.widget;

import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.google.gwt.user.client.Event;

/**
 * Created with IntelliJ IDEA. User: Han Li Date: 5/20/13
 */
public class CobraMenuItem extends MenuItem
{
    private boolean customEnabled;

    public CobraMenuItem(String label)
    {
        super(label);
    }

    /**
     * add style to the disabled widget
     * @param enabled
     */
    @Override
    public void setEnabled(boolean enabled)
    {
        this.customEnabled = enabled;
        if (!enabled)
        {
            this.addStyleName(this.disabledStyle);
        }
        else
        {
            this.removeStyleName(this.disabledStyle);
            super.setEnabled(enabled);
        }
    }

    @Override
    public void onBrowserEvent(Event event)
    {
        if (event.getTypeInt() == Event.ONMOUSEDOWN || event.getTypeInt() == Event.ONCLICK)
        {
            if(!customEnabled)
            {
                // return directly so that no action would be taken.
                return;
            }
        }
        super.onBrowserEvent(event);
    }

    /**
     * overwrite the onClick by adding our own 'customEnabled' flag
     * @param be
     */
    @Override
    protected void onClick(ComponentEvent be) {
        be.stopEvent();
        MenuEvent me = new MenuEvent(parentMenu);
        me.setItem(this);
        me.setEvent(be.getEvent());
        if (customEnabled && !disabled && fireEvent(Events.Select, me)) {
            handleClick(be);
        }
    }
}

By adding these code, we can disable the click action as well as display a “disabled” widget to user.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s