Comment générer des évènements dans un Composite Widget GWT

Publié le 8 Février 2013

Dans GWT pour créer de nouveaux widgets il est d'usage d'étendre la classe Composite. Je n'ai pas rencontré de problème pour créer les widgets par contre pour générer des évènements lors d'un changement de valeur dans le widget ça n'a pas été aussi simple.

J'ai opté pour une solution utilisant les ValueChangeEvent. L'implémentation est assez simple mais c'est surtout le manque de documentation qui pêche.

Voilà comment faire un composite qui génère des ValueChangeEvent:

 

public class DateTimePicker extends Composite implements HasValueChangeHandlers<Date>{

   private final HorizontalPanel content = new HorizontalPanel();
   private final DateBox dateBox = new DateBox();
   private final ListBox timeListBox = new ListBox();

   public DateTimePicker(){
      dateBox.setFormat(new DefaultFormat(DateTimeFormat.getFormat("yyyy-MM-dd")));
      content.add(dateBox);
      content.add(timeListBox);
      initWidget(content);
      registerHandlers();
      fillInTimeListBox();
   }

   private void registerHandlers(){
      // On enregistre des handler pour être notifié des changements dans nos composants
      dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
         @Override
         public void onValueChange(ValueChangeEvent<Date> arg0) {
            DateTimePicker.this.onValueChange();
         }
      });
      timeListBox.addChangeHandler(new ChangeHandler() {
         @Override
         public void onChange(ChangeEvent arg0) {
            DateTimePicker.this.onValueChange();
         }
      });
   }

   private void fillInTimeListBox(){
      NumberFormat format = NumberFormat.getFormat("00");
      for(int i = 0; i < 24; i++){
         timeListBox.addItem(format.format(i)+":00"); 
      }
   }

   public Date getValue(){
      String date = dateBox.getTextBox().getText();
      if(date != null && !date.isEmpty()){
         String time = timeListBox.getValue(timeListBox.getSelectedIndex());
         Date value = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm").parse(date+" "+time);
         return value;
      }
      return null;
   }

   @Override
   public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Date> handler) {
      // permet à d'autres objets de s'enregistrer pour recevoir des ValueChangeEvents
      return addHandler(handler, ValueChangeEvent.getType());
   }

   private void onValueChange(){
      // lance l'évènement, appelé lors des changements dans la dateBox ou la ListBox
      ValueChangeEvent.fire(this, getValue());
   }
}   

Rédigé par Bliz

Publié dans #GWT

Repost0
Pour être informé des derniers articles, inscrivez vous :
Commenter cet article