第二個範例 (Part IV):新增
The following examples had been tested on Mozilla's Firefox and Microsoft's IE. The document is provided as is. You are welcomed to use it for non-commercial purpose.Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu
請勿轉貼
看其他教材
新增待辦資料
顯示完所有的待辦事項後,需要完成的就剩下視窗下半部的新增、修改、以及 刪除。一般來說,這三個步驟習慣上會先實作新增;新增的資料顯示後,我們 緊接著實作修改;等到修改後的資料也正確了,最後就實作刪除,把剛剛新增的 資料除去。 在使用者按下"新增"按鈕之後,這會觸發一個事件,因此我們需要定義一個 該事件的處理方法,在本範例中稱之為 add()。add() 方法需要完成的事情包含 從輸入欄位取得資料,然後把資料新增到資料庫,最後重新更新畫面。首先, 我們先註冊事件,必須更改新增的按鈕標籤如下:<button label="新增" width="46px" height="24px" onClick="add()"/>
void add() {
}
Event newEvt = new Event(UUID.randomUUID().toString(),
name.value,priority.value.intValue(),date.value);
evtdao.insert(newEvt);
allEvents = evtdao.findAll();
01 Listitem li = new Listitem();
02 li.setValue(newEvt); // 在之後的 update, delete 會用到
03 li.appendChild(new Listcell(name.value));
04 li.appendChild(new Listcell(priority.value.toString()));
05 li.appendChild(new Listcell(new SimpleDateFormat("yyyy-MM-dd").format(date.value)));
06 box.appendChild(li);
最後,就是把欄位資料清空,清空的方式非常簡單,直接把欄位值設定為 null 即可;例如,把 name 欄位的資料清空的方式就是 name.value = null;; 其他兩個欄位也比照辦理即可。執行整個程式碼,並新增資料後的畫面如下:
void add() {
// 從輸入欄位取得資料
Event newEvt = new Event(UUID.randomUUID().toString(),
name.value,priority.value.intValue(),date.value);
// 將資料新增至資料庫
evtdao.insert(newEvt);
// 確保 allEvents 物件有最新的資料
allEvents = evtdao.findAll();
// 將新增資料形成一個 Listitem 物件(或者節點)
Listitem li = new Listitem();
li.setValue(newEvt); // 在之後的 update, delete 會用到
li.appendChild(new Listcell(name.value));
li.appendChild(new Listcell(priority.value.toString()));
li.appendChild(new Listcell(new SimpleDateFormat("yyyy-MM-dd").format(date.value)));
// 將 Listitem 物件變成 box 的子節點
// box 是 listbox 的 id 值
box.appendChild(li);
// 清除輸入欄位
name.value = null;
priority.value = null;
date.value = null;
}
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu
沒有留言:
張貼留言