Set vaadin table height to fit contents
I was solving a similar problem: I wanted a table to grow as I added rows to it. I didn't care about its exact height, as long as it showed all the rows of data, and grew as I added rows. I also wanted the table to always show some extra space at the bottom.
The core idea here is that I did three things:
- Do not call
setHeight()
for the table. - I used
setPageLength()
to define table height by rows--by how many rows high the table should be. - I called
requestRepaint()
on the element I resized. If I resized a column element, I called it on the column element. If I resized the table, I called it on the table.
Here's a generalized code sample showing how I solved this problem. My code isn't complete, but it might help you get started.
public class MyClass extends Table {
public MyClass(...)
{
this.setWidth("100%"); // fill parent <td>'s width, allows draggable sizing.
// note: do NOT setHeight().
setupColumns(); // details not shown here
setupBehavior(); // details not shown (listeners, etc)
addDataToTable(); // details not shown
adjustHeight();
}
// I also have a function to add rows to the table when
// a button is clicked. That function calls adjustHeight() (shown below).
public void adjustHeight()
{
this.setPageLength(this.getItemIds().size() + 1);
this.requestRepaint();
}
}
[EDIT/FOLLOW-UP] I've found that using this method tends to cause unnecessary scroll bars to be rendered on tables if you are using setColumnExpandRatio()
(dynamic column widths). So just as a heads-up, you should use fixed width columns (setColumnWidth()
) if you use the trick I showed above.
gdantimi
Updated on June 09, 2022Comments
-
gdantimi almost 2 years
I use CustomLayout in my project to separate UI object and their style.
I have some problem with tables.
I define a div and I want the table's height set to div's height.
Which is the best way?
I thought:
table.setsizeFull() ; table.setPageLength(0);
in the code, but the result is not what I want. I want the table full sized in div's dimensions, both with or without elements inside.
Any suggest?
-
Billy Moat over 11 yearsI'm not sure sure if it will help but "length" is spelled wrong in your example.
-
gdantimi over 11 yearsMy fault, but it is not the problem, thanks!
-
Billy Moat over 11 yearsI don't have a clue about Vaadin so this may not help but here's how you could do it with CSS: jsfiddle.net/HVk5r
-
gdantimi over 11 years@BillyMoat it is a little bit more complex
-