最佳答案
我能想到的最简单的方法是定义自己的 CSS 类和样式生成器,这与我在处理表格时所做的非常相似。
@Theme("mytheme")
@Widgetset("com.matritza.MyAppWidgetset")
public class MyUI extends UI {
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
// meh, default stuff
}
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
// create a grid
Grid grid = new Grid("Grid test");
// create a specific container for the grid to hold our persons
BeanItemContainer<Person> container = new BeanItemContainer<>(Person.class);
grid.setContainerDataSource(container);
// define our own style generator
grid.setCellStyleGenerator(new Grid.CellStyleGenerator() {
@Override
public String getStyle(Grid.CellReference cellReference) {
if ("age".equals(cellReference.getPropertyId())) {
// when the current cell is number such as age, align text to right
return "rightAligned";
} else {
// otherwise, align text to left
return "leftAligned";
}
}
});
// generate some dummy data
for (int i = 0; i < 10; i++) {
container.addItem(new Person("Name " + i, "Surname " + i, i));
}
layout.addComponent(grid);
}
// basic class to populate the grid in a fast & simple way
public class Person {
private String name;
private String surname;
private int age;
private Person(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
以及基本的 CSS 样式
@mixin mytheme {
@include valo;
// Insert your own theme rules here
.leftAligned {
text-align: left;
}
.rightAligned {
text-align: right;
}
}
你应该会看到类似
顺便说一句,在 Java 8 及更高版本中,该样式生成器的新 Lambda 语法将是:
grid.setCellStyleGenerator(( Grid.CellReference cellReference ) -> {
if ( "age".equals( cellReference.getPropertyId() ) ) {
// when the current cell is number such as age, align text to right
return "rightAligned";
} else {
// otherwise, align text to left
return "leftAligned";
}
});
关于vaadin - 在 Vaadin Grid 中右对齐列内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29291741/