PDA

View Full Version : Close MessageBox



A.Rothe
11 Nov 2011, 6:47 AM
Hi,

I have a MessageBox, which returns a name for my ModelData. My code:



final MessageBox box = new MessageBox();

box.setTitle("Name");
box.setMessage("Name:");
box.setType(MessageBoxType.PROMPT);
box.setButtons(MessageBox.OKCANCEL);
box.getDialog().setHideOnButtonClick(false);
box.setClosable(true);

box.addCallback(new Listener<MessageBoxEvent>() {
public void handleEvent(MessageBoxEvent be) {

// close always on Cancel
if ("Cancel".equals(be.getButtonClicked().getText())) {
box.close();
return;
}

// leave it open if empty
if (be.getValue() == null) {
be.setCancelled(true);
be.stopEvent();
return;
}

if ("".equals(be.getValue().trim())) {
be.stopEvent();
be.setCancelled(true);
return;
}

// leave it open, if the name already exists
if (store.findModel("name", be.getValue()) != null) {
be.stopEvent();
be.setCancelled(true);
return;
}

box.close();

// do something with the name
Info.display("hohoho", "new name " + be.getValue());
}
});


But the MessageBox is always open, I cannot close it. What is wrong?

Thanks
Andre :-?

WesleyMoy
14 Nov 2011, 7:33 PM
The callback you added will never execute. The documentation for MessageBox.addCallback (http://www.sencha.com/gxtdocs/#com.extjs.gxt.ui.client.widget.MessageBox) reads that these callbacks will execute when the message box is closed. Your code won't execute until the message box is closed in some other way.

You can test this by closing the message box with the close button in the header. You'll see a null pointer exception on this line:


if ("Cancel".equals(be.getButtonClicked().getText())) {

This is because the callback is now executing and none of the buttons at the bottom of the message box were clicked. be.getButtonClicked() will return null.

Instead, consider adding separate listeners to each button.


Dialog dialog = box.getDialog();

dialog.getButtonById(Dialog.CANCEL).addSelectionListener(
new SelectionListener<ButtonEvent>() {

@Override
public void componentSelected(ButtonEvent event) {
// close always on Cancel
box.close();
}

});

dialog.getButtonById(Dialog.OK).addSelectionListener(new SelectionListener<ButtonEvent>() {

@Override
public void componentSelected(ButtonEvent event) {
String value = box.getTextBox().getValue();

// leave it open if empty
if (value == null) {
return;
}

if ("".equals(value.trim())) {
event.stopEvent();
event.setCancelled(true);
return;
}

// leave it open, if the name already exists
if (store.findModel("name", value) != null) {
event.stopEvent();
event.setCancelled(true);
return;
}

box.close();

// do something with the name
Info.display("hohoho", "new name " + value);
}

});

As a bonus, this uses Dialog's constants for Ok and Cancel. This removes any dependency of your code on the text of the button, making your code less fragile.

A.Rothe
14 Nov 2011, 11:47 PM
Thanks a lot!
Andre