Wicket Examples - guestbook編 -
「サンプルのソースを見る」の第6回guestbook編。このサンプルでは、
- ListViewコンポーネントのモデルオブジェクトを変更して通知する方法
がなんとなくわかります(^_^;)。
アプリケーションクラス(GuestBookApplication.java)
まずは、アプリケーションクラスです。こちらは、ホームページクラスを返しているだけなので、割愛します。
Pageクラス(GuestBook.java)
次に、Pageクラスです。
public final class GuestBook extends WicketExamplePage {
Commentインスタンスを格納するリスト(commentList)と、ListViewです。commentListがstaticとなっており、全ユーザからの情報が追加・参照されるようです。
private static final List commentList = new ArrayList(); private final ListView commentListView;
コンストラクタでは、Formのインスタンスを追加し、ListViewコンポーネントのインスタンスを追加しています。populateItemメソッドでは、入力内容であるCommentインスタンスの、日付をLabelコンポーネントに、入力テキストをMultiLineLabelコンポーネントに設定しています。setVersionedメソッドを引数をfalseで呼び、バージョニングをしないようにしています・・・なんのことやらですが(^_^;)
public GuestBook() { add(new CommentForm("commentForm")); add(commentListView = new ListView("comments", commentList) { public void populateItem(final ListItem listItem) { final Comment comment = (Comment)listItem.getModelObject(); listItem.add(new Label("date", new Model(comment.getDate()))); listItem.add(new MultiLineLabel("text", comment.getText())); } }).setVersioned(false); }
次にFormコンポーネントです。
public final class CommentForm extends Form {
コンストラクタでは、スーパークラスのコンストラクタを呼んで、TextAreaコンポーネントを追加しています。
public CommentForm(final String id) { super(id, new CompoundPropertyModel(new Comment())); add(new TextArea("text")); }
Submitボタンが押下された時に呼ばれるonSubmitメソッドをオーバーライドします。モデルオブジェクトであるCommentクラスのインスタンスを取得し、それをもとに新たなCommentインスタンスを生成します。生成したインスタンスに現在の日付を設定して、commentListの先頭に追加するわけですが、追加する前にListView#modelChangingメソッドを、追加したあとにListView#modelChangedメソッドを呼ぶことで、ListViewに反映を通知しているようです。
public final void onSubmit() { // Construct a copy of the edited comment final Comment comment = (Comment)getModelObject(); final Comment newComment = new Comment(comment); // Set date of comment to add newComment.setDate(new Date()); // Add the component we edited to the list of comments commentListView.modelChanging(); commentList.add(0, newComment); commentListView.modelChanged(); // Clear out the text component comment.setText(""); } }