最近作りたい物ができ、それに使うパーツでトグルボタンが並んでいて、1だけが押された状態になるようなものが欲しかった。ラジオボタンをトグルボタンに置き換えたような物を作りたかった。イメージは
横バージョン
縦バージョン
こんな感じ。文字列はめんどくさいので数字だけにした。それで作り始めたころに気づいた。「それ、タブの画像と文字列を変えればできるよ」と…しかし、経験は多いほうがいいと思った俺はこのタブらしきものを作った。以下ソース。イベントハンドラーの追加はできるけど、削除ができない。どうしたらいいのか不明。Widget#removeHandlerとかあるのかと思ったがなかった。
簡単な使い方、コンストラクタの引数はボタンの数と方向。オーバーロードで引数の省略版あり、デフォルトの値はボタンの数が5、方向は水平方向(ToEast)。
SwitchButton switches = new SwitchButton(5, SwitchButton.Direction.ToSouth); switches.addSelectionHandler(new SelectionHandler<Integer>(){ public void onSelection(SelectionEvent<Integer> e){ int number = e.getSelectedItem() + 1; Window.alert(Integer.toString(number)); } });
ソース
import java.util.List; import java.util.ArrayList; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ToggleButton; import com.google.gwt.user.client.ui.CellPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; public class SwitchButton extends Composite implements HasSelectionHandlers<Integer>{ protected int count; protected List<ToggleButton> buttons; protected CellPanel panel; protected Direction direction; protected List<SelectionHandler<Integer>> handlers; public enum Direction{ ToEast, ToSouth}; public SwitchButton(){ this(5, Direction.ToEast); } public SwitchButton(int count){ this(count, Direction.ToSouth); } public SwitchButton(int count, Direction direction){ this.count = count; this.direction = direction; this.buttons = new ArrayList<ToggleButton>(); this.handlers = new ArrayList<SelectionHandler<Integer>>(); if(direction == Direction.ToEast){ this.panel = new HorizontalPanel(); }else if(direction == Direction.ToSouth){ this.panel = new VerticalPanel(); }else{ this.panel = new HorizontalPanel(); } for(int i = 0; i < count; i++){ final int index = i; ToggleButton button = new ToggleButton(Integer.toString(i + 1)); this.buttons.add(button); this.panel.add(button); button.addClickHandler(new ClickHandler(){ public void onClick(ClickEvent e){ selectButton(index); SelectionEvent.fire(SwitchButton.this, index); } }); } selectButton(0); initWidget(this.panel); } public void selectButton(int index){ for(int i = 0; i < this.buttons.size(); i++){ ToggleButton button = this.buttons.get(i); if(i == index){ button.setDown(false); }else{ button.setDown(true); } } } @Override public HandlerRegistration addSelectionHandler(SelectionHandler<Integer> handler){ return addHandler(handler, SelectionEvent.getType()); } }