无聊啊,没事干,到网上找点开源的东西看看,发现一个叫SwiXml的东西可以用xml来描述界面,蛮有意思,遂下载了个看看。
SwiXml是一个很小的gui生成引擎,它使你可以在xml文件中描述界面,而在运行期动态的生成javax.swing包里面的对象,而不用在代码中写死。其实这种东西以前别的项目已经做过,比如Thinlet, XUL, XULUX, Jelly, and SwingML, 但是我一看,觉得它这个名字太自然了Swing + Xml 看着亲切, 就决定拿这个过来看看, 下面是SwiXml官网(http://www.swixml.org)说的SwiXml与其他项目的不同之处:
import org.swixml.SwingEngine;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
public class HelloWorld ...{
/** *//** submit counter */
private int clicks;
/** *//** JTextField member gets instantiated through Swixml (look for id="tf" in xml descriptor) */
public JTextField tf;
/** *//** Jlabel to display number of button clicks */
public JLabel cnt;
/** *//** Action appends a '#' to the textfields content. */
public Action submit = new AbstractAction() ...{
public void actionPerformed( ActionEvent e ) ...{
tf.setText( tf.getText() + '#' );
cnt.setText(String.valueOf( ++clicks ));
}
};
/** *//** Renders UI at construction */
private HelloWorld() throws Exception ...{
System.out.println( new File( "" ).getAbsolutePath() );
new SwingEngine( this ).render( "xml/helloworld.xml" ).setVisible( true );
}
/** *//** Makes the class bootable */
public static void main( String[] args ) throws Exception ...{
new HelloWorld();
}
}
相应的xml配置文件:
<frame size="640,280" title="Hello SWIXML World" defaultCloseOperation="JFrame.EXIT_ON_CLOSE">
<panel constraints="BorderLayout.CENTER">
<label labelfor="tf" font="Courier New-BOLD-12" foreground="blue" text="Hello World!"/>
<textfield id="tf" columns="20" Text="Swixml"/>
<button text="Click Here" action="submit"/>
</panel>
<panel constraints="BorderLayout.SOUTH">
<label font="Courier New-BOLD-36" text="Clicks:"/>
<label font="Courier New-BOLD-36" id="cnt"/>
</panel>
</frame>
效果如下:
结论:
上面只是一个HelloWord的例子,我们可以利用swixml来让用户配置界面,许多软件比如:office, maxthon都提供用户一个界面让用户增添按钮,有了swixml,在java里面实现可配置界面将变得极为方便。
参考资料:
SwiXml官网: http://www.swixml.org.
Java开源大全:http://www.open-open.com 罗列了大量的Java开源 的资料,只要你能想到的,在这里都能找得到。