Groovy中有一个有趣的方法:SwingBuilder。 例如:
swing.edt {
frame(title:'Frame', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show:true) {
vbox {
textlabel = label("Click the button!")
button(
text:'Click Me',
actionPerformed: {
count++
textlabel.text = "Clicked ${count} time(s)."
println "Clicked!"
}
)
widget(sharedPanel())
widget(sharedPanel())
}
}
}
我认为,它使代码更具可读性和可维护性。 我在Java中使用类似的方法来处理Swing或Vaadin应用程序。
示例:
@Theme("mytheme")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI {
private VerticalLayout layout;
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "i.x.songbook.main.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
setContent(layout = new VerticalLayout() {
{
setMargin(true);
addComponent(new HorizontalLayout() {
{
setWidth("100%");
{
Label expandingGap = new Label();
expandingGap.setWidth("100%");
addComponent(expandingGap);
setExpandRatio(expandingGap, 5f);
}
{
Label titleLabel = new Label("<center>Title</center>",
ContentMode.HTML);
addComponent(titleLabel);
setExpandRatio(titleLabel, 30f);
}
{
Label fixedGap = new Label();
fixedGap.setWidth("10px");
addComponent(fixedGap);
}
{
TextField searchField = new TextField();
searchField.setWidth("100%");
searchField.setDescription("Search");
addComponent(searchField);
setExpandRatio(searchField, 50f);
}
{
Label expandingGap = new Label();
expandingGap.setWidth("100%");
addComponent(expandingGap);
setExpandRatio(expandingGap, 5f);
}
}
});
addComponent(new Button("Button") {
{
addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
}
});
}
});
}
});
}
}
答案 0 :(得分:1)
它无缘无故地创造了无数的匿名内部类。
我同意使用{}
对组件进行分组,但我不认为匿名类是合理的,例如。
// This is unnecessary and unjustified:
setContent(layout = new VerticalLayout() {
// ...
});