用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開源   的資料,只要你能想到的,在這裏都能找得到。


 



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