用xml来表示界面

   无聊啊,没事干,到网上找点开源的东西看看,发现一个叫SwiXml的东西可以用xml来描述界面,蛮有意思,遂下载了个看看。
   SwiXml是一个很小的gui生成引擎,它使你可以在xml文件中描述界面,而在运行期动态的生成javax.swing包里面的对象,而不用在代码中写死。其实这种东西以前别的项目已经做过,比如Thinlet, XUL, XULUX, Jelly, and SwingML, 但是我一看,觉得它这个名字太自然了Swing + Xml 看着亲切, 就决定拿这个过来看看, 下面是SwiXml官网(
http://www.swixml.org)说的SwiXml与其他项目的不同之处:

 SwiXml differentiates itself from the rest by focusing  completely on javax.swing. 
 Programmers who know Swing already can immediately start writing descriptors. No 
 additional XML dialect has to be learned: Class names translate into tag names and 
 method names into attribute names. 
 SwiXml is faster since no additional layers had to be added on top of the Swing objects. 
 
 SwiXml is smaller. Despite the fact that the swixml jar file is only about 40 Kbyte 
 in size, almost all of the infamous Swing objects are supported. 
 SwiXml does Java Swing GUI generation and that is all. The dynamic behavior of the 
 user interface, defining the application's business rules, has to be coded in Java. 
下面是个例子:

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配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<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>


效果如下:

GUI IMGAGE

结论:
上面只是一个HelloWord的例子,我们可以利用swixml来让用户配置界面,许多软件比如:office, maxthon都提供用户一个界面让用户增添按钮,有了swixml,在java里面实现可配置界面将变得极为方便。

参考资料:
  SwiXml官网:
http://www.swixml.org.
  Java开源大全:
http://www.open-open.com 罗列了大量的Java开源   的资料,只要你能想到的,在这里都能找得到。


 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章