I have a Vaadin Table with some columns that can have widely-varying content widths. Sometimes there might be no rows with more than a few characters in them; other times, there might be rows with enough text to fill a screen.
I want to set an explicit column width to prevent the column from taking up too much space by default. This can be done with Table#setColumnWidth
. However, if all values for the column are shorter than that specified width, I would like to revert to auto-sizing, so that the column is only as wide as it needs to be.
In all cases, I still want the column to be manually resizable.
Essentially, I want to say 'auto-size, up to a maximum width of x
'. Is there a way to do this?
It is possible. You will need to jump into Javascript. SSCCE:
@com.vaadin.annotations.JavaScript("main.js")
public class QwertUI extends UI {
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = QwertUI.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
final Table table = new Table("The Brightest Stars");
table.addContainerProperty("Name", String.class, null);
table.addContainerProperty("Mag", Float.class, null);
Object newItemId = table.addItem();
Item row1 = table.getItem(newItemId);
row1.getItemProperty("Name").setValue("Sirius");
row1.getItemProperty("Mag").setValue(-1.46f);
// Add a few other rows using shorthand addItem()
table.addItem(new Object[]{"Canopus", -0.72f}, 2);
table.addItem(new Object[]{"Arcturus", -0.04f}, 3);
table.addItem(new Object[]{"Alpha Centaurissssssssssssssssssssssssssssssssssssssssssss", -0.01f}, 4);
JavaScript.getCurrent().addFunction("YouAreWelcome", new JavaScriptFunction(){
@Override
public void call(JsonArray arguments)
{
Object o = arguments.get(0).asString();
table.setColumnWidth("Name", new Integer(o.toString()));
}
});
JavaScript.getCurrent().execute("WeChooseToGoToTheMoon()");
table.setPageLength(table.size());
layout.addComponent(table);
}
}
And main.js
function WeChooseToGoToTheMoon(){
var myMaxWidth = 200;
var elements = document.getElementsByClassName("v-table-cell-content");
var maxSize = -1;
for(i=0; i<elements.length; i++){
if(elements[i].clientWidth > maxSize){
maxSize = elements[i].clientWidth;
}
}
if(maxSize < myMaxWidth){
YouAreWelcome(maxSize);
}else{
YouAreWelcome(myMaxWidth);
}
}
You may need to adjust the javascript to suit your needs.