2014-01-13 28 views
3

我應該將列添加到具有BeanItemContainer數據源的表中。使用BeanItemContainer添加表列

這是我的情況:

我在vaadin面板哈瓦實體bean

@Entity 
public class MyBean implements { 

@Id 
private Long id; 

//other properties 

}

那麼我這個方法

private Table makeTable(){ 

    Table table = new Table(); 
    tableContainer = new BeanItemContainer<MyBean>(MyBean.class); 
    table.setContainerDataSource(tableContainer); 

    table.setHeight("100px"); 
    table.setSelectable(true); 
    return table; 

} 

現在,我想添加一個應該讓我能夠刪除此容器中的項目的列。

我該怎麼辦?

回答

6

您可以創建一個ColumnGenerator,它爲您創建按鈕。 看一看here

例子:

比方說,我們有一個爲myBean類:然後

public class MyBean { 

    private String sDesignation; 
    private int iValue; 

    public MyBean() { 
    } 

    public MyBean(String sDesignation, int iValue) { 
     this.sDesignation = sDesignation; 
     this.iValue = iValue; 
    } 

    public String getDesignation() { 
     return sDesignation; 
    } 

    public int getValue() { 
     return iValue; 
    } 

} 

我們可以創建一個表,生成列賦予一個按鈕,刪除當前項目。

Table table = new Table(); 

BeanItemContainer<MyBean> itemContainer = new BeanItemContainer<MyBean>(MyBean.class); 
table.setContainerDataSource(itemContainer); 

table.addItem(new MyBean("A", 1)); 
table.addItem(new MyBean("B", 2)); 

table.addGeneratedColumn("Action", new ColumnGenerator() { // or instead of "Action" you can add "" 
    @Override 
    public Object generateCell(final Table source, final Object itemId, Object columnId) { 
     Button btn = new Button("Delete"); 
     btn.addClickListener(new ClickListener() { 
      @Override 
      public void buttonClick(ClickEvent event) { 
       source.removeItem(itemId); 
      } 
     }); 
     return btn; 
    } 
}); 

table.setVisibleColumns(new Object[]{"designation", "value", "Action"}); // if you added "" instead of "Action" replace it by "" 
+0

我試圖用這個解決方案,但我得到java.lang.NoClassDefFoundError上table.addGeneratedColumn(「」,新ColumnGenerator()。爲什麼呢? – Skizzo

+0

@Marco更新了我從一個工作示例答案。 – nexus

+0

由於現在一切正常 – Skizzo

0

我會建議使用shourtcut代替:

table.addShortcutListener(new ShortcutListener("Delete", KeyCode.DELETE, null) { 

     @Override 
     public void handleAction(final Object sender, 
           final Object target) { 
      if (table.getValue() != null) { 
       // here send event to your presenter to remove it physically in database 
       // and then refresh the table 
       // or just call tableContainer.removeItem(itemId) 
      } 
     } 
    }); 

,如果你不想讓你將需要添加列,如shourtcuts:

table.addContainerProperty("Delete", Button.class, null); 

,然後放在那裏的按鈕,會做同樣的行動。