クリックしたら色が変わるボタン
以上を応用して、クリックしたら色が変わるボタンを作成してみた。デフォルトは図1のような通常のボタンだが、クリックするごとに図2のように色を変え、4回目のクリックで元のデフォルトに戻るというものだ。
ソースコードをリスト2(HTML)、リスト3(Java)に示す。筆者の環境ではHosted modeはもちろん、Web mode(コンパイル)でもFirefox 2.0.0.7とIE7で実行を確認している。リストの詳細は字数の関係から割愛させていただくが、前述した説明を参考にして、ぜひGWTアプリケーションを体験していただきたい。
リスト2 ボタンなどを表示するHTML
GWTのウィジェット表示
GWTのウィジェット表示
ボタンをクリックすると、色が変わります。
スタイル
リスト3 GWTによるJavaアプリケーション
package gwt.exmaple.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
public class ColorChangeableButton implements EntryPoint {
public void onModuleLoad() {
final Button button = new Button( "色が変わるボタン" );
final Label label = new Label( button.getStyleName() );
button.addClickListener( new ClickListener() {
// スタイルシートの名称
String[] style = { "gwt-button", "button-blue",
"button-yellow", "button-red" };
// スタイルシート切り替え用
int idx = 0;
// クリックされたらスタイルシートを変更
public void onClick( Widget sender ) {
idx = ( ++idx % ( style.length ) );
label.setText( style[ idx ] );
button.setStyleName( style[ idx ] );
}
});
RootPanel.get( "div-label" ).add( label );
RootPanel.get( "div-button" ).add( button );
}
}