簡體   English   中英

在Vaadin中為網格的每一行添加一個鼠標監聽器

[英]Add a mouse-listener to each row of a grid in Vaadin

我的Web應用程序中有一個簡單的網格,編碼如下:

Grid users_list = new Grid();
users_list.addColumn("username", String.class);
users_list.addColumn("email", String.class);

我想在每個填充網格的條目中添加一個鼠標監聽器(鼠標左鍵)。 Vaadin有可能嗎?

要么使用SelectionListener,要么實現純JavaScript解決方案。 SSCCE為此:

protected void init(VaadinRequest request)
{
    VerticalLayout layout = new VerticalLayout();
    Collection<Person> people = new ArrayList<Person>();
    people.add(new Person("Nicolaus Copernicus", 1543));
    people.add(new Person("Galileo Galilei", 1564));
    people.add(new Person("Johannes Kepler", 1571));

    BeanItemContainer<Person> container = new BeanItemContainer<Person>(Person.class, people);
    Grid grid = new Grid(container);
    layout.addComponent(grid);

    com.vaadin.ui.JavaScript.getCurrent().addFunction("rowClicked", new JavaScriptFunction()
    {
        @Override
        public void call(JsonArray arguments)
        {
            System.out.println(arguments.get(0).toString());
        }
    });
    com.vaadin.ui.JavaScript.getCurrent().execute("addRowListener()");

    setContent(layout);
}

JavaScript的:

function addRowListener() {
var table = document.getElementsByClassName("v-grid-tablewrapper")[0];
table = table.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
     var currentRow = table.rows[i];
     var createClickHandler = 
     function(row) 
     {
         return function() { 
                                var cell = row.getElementsByTagName("td")[0];
                                    var id = cell.innerHTML;
                                    rowClicked(id);
                           };
     };

    currentRow.onclick = createClickHandler(currentRow);
}
}

您可以使用MainUI類頂部的import com.vaadin.annotations.JavaScript注釋來附加JavaScript。 您需要將JavaScript文件放在與MainUI類完全相同的包中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM