是否有可能使用Java Lambdas来实现类似Groovy的SwingBuilder?

问题描述:

我只想到,在Lambdas中可能会在本地Java中构建像SwingBuilder这样的东西 - 但是看起来如果这是可能的话,现在已经完成了。是否有可能使用Java Lambdas来实现类似Groovy的SwingBuilder?

这有什么理由不能做,或者它已经完成了吗?

我意识到这与SwingBuilder like GUI syntax for Java?类似,但我希望将Lambdas添加到组合中。 SwingBuilder大多建立在Lambdas之上,这在Java 8之前是绝对不可能的。它还使用了一些动态编程,显然不能使用它,因此它永远不会是干净的,但我认为它是可能的。

+0

应该可以结束,你不会得到missingProperty东西的好处,但通过名称来获得控件...虽然我会将JavaFX作为目标,因为Swing在出门的时候很好 –

首先,我们必须确定我们想要解决哪些问题。最大的问题是创建简单的事件绑定,这需要在以前的Java版本中使用内部类。在大多数情况下,这可以替换为单方法侦听器接口的lambda表达式,对于多方法接口,您需要适配器,如thisthat Q & A中讨论的那样,但这只能进行一次。

另一个问题是初始化代码的结构。原则上,命令式代码工作正常,但如果要修改要添加到容器中的某个组件的某些属性,则必须更改container.add(new ComponentType());以引入一个新的局部变量,以供后续语句使用。另外,添加到容器本身需要将其保存在一个变量中。虽然Java允许用大括号来限制局部变量的范围,但结果仍然很笨拙。

这是最好的起点。如果我们使用,例如

public class SwingBuilder { 
    public static <T> T build(T instance, Consumer<T> prepare) { 
     prepare.accept(instance); 
     return instance; 
    } 
    public static <T extends Container> T build(
             T instance, Consumer<T> prepare, Component... ch) { 
     return build(build(instance, prepare), ch); 
    } 
    public static <T extends Container> T build(T instance, Component... ch) { 
     for(Component c: ch) instance.add(c); 
     return instance; 
    } 
} 

这些简单的通用方法已经很安静了,因为它们可以组合。使用import static,一个使用的网站能像

JFrame frame = build(new JFrame("Example"), 
    f -> { 
     f.getContentPane().setLayout(
      new BoxLayout(f.getContentPane(), BoxLayout.LINE_AXIS)); 
     f.setResizable(false); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    }, 
    build(new JLabel("\u263A"), l -> l.setFont(l.getFont().deriveFont(36f))), 
    Box.createHorizontalStrut(16), 
    build(new JPanel(new GridLayout(0, 1, 0, 5)), 
     new JLabel("Hello World"), 
     build(new JButton("Close"), b -> { 
      b.addActionListener(ev -> System.exit(0)); 
     }) 
    ) 
); 
frame.pack(); 
frame.setVisible(true); 

相比Groovy中,我们还是要使用一个变量来表示方法调用的对象更改属性,但这些变量可以使用类被声明为简单name ->通过lambda表达式实现Consumer时推断。而且,变量的作用域会自动限制到初始化的持续时间。

使用这个起始点,您可以为经常使用的组件和/或经常使用的属性以及为多方法侦听器提到的工厂方法添加专门的方法。例如。

public static JFrame frame(String title, Consumer<WindowEvent> closingAction, 
          Consumer<? super JFrame> prepare, Component... contents) { 
    JFrame f = new JFrame(title); 
    if(closingAction!=null) f.addWindowListener(new WindowAdapter() { 
     @Override public void windowClosing(WindowEvent e) { 
      closingAction.accept(e); 
     } 
    }); 
    if(prepare!=null) prepare.accept(f); 
    final Container target = f.getContentPane(); 
    if(contents.length==1) target.add(contents[0], BorderLayout.CENTER); 
    else { 
     target.setLayout(new BoxLayout(target, BoxLayout.PAGE_AXIS)); 
     for(Component c: contents) target.add(c); 
    } 
    return f; 
} 

但我认为,图片很清楚。