Advertisement
mitrakov

GWT MessageBox Dialog

Jul 20th, 2019
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. import java.util.Optional;
  2. import com.google.gwt.event.dom.client.ClickHandler;
  3. import com.google.gwt.event.dom.client.KeyCodes;
  4. import com.google.gwt.user.client.Event;
  5. import com.google.gwt.user.client.ui.*;
  6.  
  7. public class InfoDialog extends DialogBox {
  8.     protected final Widget widget;
  9.     protected final Button btnClose = new Button("Close", (ClickHandler) e -> hide());
  10.     protected Optional<Focusable> onCloseFocusedWidget = Optional.empty();
  11.  
  12.     public InfoDialog(String title, Widget widget) {
  13.         this.widget = widget;
  14.  
  15.         final VerticalPanel mainPanel = new VerticalPanel();
  16.         final Panel buttonsPanel = new HorizontalPanel();
  17.  
  18.         mainPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
  19.         mainPanel.add(widget);
  20.         mainPanel.add(new HTML("<hr/>"));
  21.         mainPanel.add(buttonsPanel);
  22.  
  23.         buttonsPanel.setStyleName("buttons-panel");
  24.         buttonsPanel.add(btnClose);
  25.  
  26.         setText(title);
  27.         setWidget(mainPanel);
  28.     }
  29.  
  30.     public InfoDialog withOnCloseFocusable(Focusable widget) {
  31.         onCloseFocusedWidget = Optional.of(widget);
  32.         return this;
  33.     }
  34.  
  35.     public InfoDialog withButtonText(String text) {
  36.         btnClose.setText(text);
  37.         return this;
  38.     }
  39.  
  40.     @Override
  41.     public void show() {
  42.         super.show();
  43.         if (widget instanceof Focusable)
  44.             ((Focusable) widget).setFocus(true);
  45.     }
  46.  
  47.     @Override
  48.     public void center() {
  49.         super.center();
  50.         if (widget instanceof Focusable)
  51.             ((Focusable) widget).setFocus(true);
  52.     }
  53.  
  54.     @Override
  55.     public void hide() {
  56.         super.hide();
  57.         onCloseFocusedWidget.ifPresent(f -> f.setFocus(true));
  58.     }
  59.  
  60.     @Override
  61.     protected void onPreviewNativeEvent(Event.NativePreviewEvent event) {
  62.         super.onPreviewNativeEvent(event);
  63.         if (event.getTypeInt() == Event.ONKEYDOWN) {
  64.             final int code = event.getNativeEvent().getKeyCode();
  65.             switch (code) {
  66.                 case KeyCodes.KEY_ENTER:
  67.                 case KeyCodes.KEY_ESCAPE:
  68.                     hide(); break;
  69.             }
  70.         }
  71.     }
  72. }
  73.  
  74.  
  75.  
  76. // example:
  77. public static void showMessage(String title, String message) {
  78.     new InfoDialog(title, new HTML(message)).center();
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement