Andrew
Andrew

Reputation: 378

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

I have a simple grid in my web application, that is coded like this:

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

and I would like to add a mouse-listener (left mouse button) to each entry that will populate the grid. Is this possible in Vaadin?

Upvotes: 1

Views: 607

Answers (1)

kukis
kukis

Reputation: 4644

Either make use of SelectionListener or implement pure JavaScript solution. SSCCE for this:

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);
}
}

You can attach JavaScript using import com.vaadin.annotations.JavaScript annotation at top of your MainUI class. You need to put JavaScript file in the very same package as your MainUI class.

Upvotes: 3

Related Questions