Toji
Toji

Reputation: 34498

GWT focus on button in dialog

I'm having a terrible time trying to manage focus on a GWT dialog. I'm trying to put together a very keyboard-friendly interface, and so when my dialog comes up (a simple Yes/No/Cancel affair) I need to have keyboard focus automatically shift to the "Yes" button. Yet despite my best efforts I can't seem to wrangle the focus where it needs to be programatically. My code as it stands now looks like this:

public abstract class ConfirmDialog extends DialogBox {
    final Button yesBtn, noBtn, cancelBtn;

    public ConfirmDialog(String title, String prompt) {
        super(false);

        setTitle(title);
        setText(title);
        setGlassEnabled(true); // For great modal-ness!

        DockLayoutPanel buttonPanel = new DockLayoutPanel(Unit.PX);
        buttonPanel.setHeight("25px");
        buttonPanel.addEast(cancelBtn, 75);
        buttonPanel.addEast(noBtn, 60);
        buttonPanel.addEast(yesBtn, 60);

        FlowPanel dialogPanel = new FlowPanel();
        dialogPanel.add(new HTML(prompt));
        dialogPanel.add(buttonPanel);

        setWidget(dialogPanel);
    }

    @Override
    public void show() {
        super.show();
        center();
        yesBtn.setFocus(true); // Why does this hate me???
    }
}

Omitted: lots of button-click event handling gook that doesn't affect the initial display.

Anyway, as you can see from the code, the intent is that as soon as the dialog is shown the "yes" button gains focus. I've tried it as shown in the code sample, I've put the focus in a DeferredCommand, I've tried hooking other events... but at best focus is somewhat random.

I imagine it's probably just a matter of timing (maybe I'm trying to focus on the button before it's been added to the DOM?) but if so I'm at a loss as to what I should be watching to let me know when I can validly give the button focus. Any hints?

Thanks!

Upvotes: 0

Views: 5228

Answers (3)

zorro2b
zorro2b

Reputation: 2257

If you want to gain focus as opposed to capture key events, you need to defer the setFocus like this:

@Override
public void show() {
    super.show();

    Scheduler.get().scheduleDeferred(new Command() {
        public void execute() {
            yesBtn.setFocus(true);
        }
    });
}

Upvotes: 4

cxd213
cxd213

Reputation: 186

You need to override the onPreviewNativeEvent method as I've done below in your PopupPanel/DialogBox:

protected void onPreviewNativeEvent(Event.NativePreviewEvent event) {
    if(event.getTypeInt() == Event.ONKEYDOWN) {
        if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
            submitButton.click();
        }
    }
    super.onPreviewNativeEvent(event);
}

This will allow you to capture Key Events while a PopupPanel is being shown.

Upvotes: 4

barrowc
barrowc

Reputation: 10679

You could try using setTabIndex instead.

cancelBtn.setTabIndex(2);
noBtn.setTabIndex(1);
yesBtn.setTabIndex(0);

Upvotes: 1

Related Questions