SwingBuilder like GUI syntax for Java?

…衆ロ難τιáo~ 提交于 2019-12-12 19:13:39

问题


Is there a library that makes it possible to write Swing based GUIs similar to the manner done by SwingBuilder in Groovy?

I am hoping to develop a Java GUI application without embedding Groovy or another complete programming language in Java, and I find the standard Java syntax rather tedious.


回答1:


I went down this path at one point, then I found MiGLayout - unless I'm using a split pane, I can generally lay out each of my views in a single panel, with a minimum of hassle. There is a tad of a learning curve, but once you are over the hump, you can knock out a really nice looking GUI in almost no time.

The whole paradigm of nesting panels inside other panels isn't clean for a lot of designs - you wind up fighting the layout manager.




回答2:


I'm not aware of such a library, though something similar would be possible (without named parameters, though, which reduces readability). Someone may have converted SwingBuilder to java.

[Looks like you can get java source for SwingBuilder at http://kickjava.com/src/groovy/swing/SwingBuilder.java.htm. I don't know how current that is]

About the closest you can come in plain java is to use the "double curly trick" (which isn't really a trick, just an anonymous inner class definition).

The SwingBuilder example on your referenced page:

new SwingBuilder().edt {
    frame(title:'Frame', size:[300,300], show: true) {
    borderLayout()
    textlabel = label(text:"Click the button!", constraints: BL.NORTH) 
    button(text:'Click Me',
           actionPerformed: {
               count++;
               textlabel.text = "Clicked  ${count} time(s).";
               println "clicked"},
               constraints:BL.SOUTH)
    }
}

could be written something like the following in Java

new JFrame() {{
    setTitle("Frame");
    setSize(300,300);
    setLayout(new BorderLayout());
    textlabel = new JLabel("Click the button!");
    add(textlabel, BorderLayout.NORTH);
    add(new JButton("Click Me") {{
        addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                count++;
                textlabel.setText("Clicked " + count + " time(s).");
                System.out.println("clicked");
        }});
    }}, BorderLayout.SOUTH);
    setVisible(true);
}};

NOTE: The problem here is that when you use

new SomeClass() {{ ... }}

it's actually creating a new class definition. I wouldn't recommend doing it very often because of this.



来源:https://stackoverflow.com/questions/4018817/swingbuilder-like-gui-syntax-for-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!