DropDownChoiceを使ってみるのAjax版を作ってみた。ボタンを押さなくてもDropDownChoiceで値を選んだときにラベルに選んだ値を表示するようにした。変更を加えたHTMLとJavaのファイルだけを載せておく
DropDownTest.html 不要になったボタンを削除した
<html> <head> <title>DropDownTest</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <form wicket:id="form"> <select wicket:id="choice"> <option>テスト1</option> <option>テスト2</option> </select> </form> <span wicket:id="yourChoice">あなたが選んだのはテスト1です</span> </body> </html>
DropDownTest.java
package dropdown; import java.util.List; import java.util.Arrays; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; public class DropDownTest extends WebPage{ public DropDownTest(){ //submitボタンを押したときにDropDownChoiceで選んだ項目を表示する final Label label = new Label("yourChoice", new Model()); //Ajaxのイベントで更新するために必要なコード label.setOutputMarkupId(true); Form form = new Form("form"); //DropDownChoiceに表示させるリスト List testList = Arrays.asList(new String[]{"テスト1", "テスト2", "テスト3"}); final DropDownChoice choice = new DropDownChoice("choice", new Model(), testList); //DropDownChoiceの選択された値が変わったときにラベルを更新する choice.add(new AjaxFormComponentUpdatingBehavior("onchange"){ public void onUpdate(AjaxRequestTarget target){ String selectedText = choice.getModelObjectAsString(); if(selectedText.isEmpty()) return; String text = "あなたが選んだのは"; text += selectedText; text += "です"; label.setModelObject(text); //Ajaxのイベントでラベルを更新する target.addComponent(label); } }); add(label); form.add(choice); add(form); } }