我的第一个Swing程序

类别:Java 点击:0 评论:0 推荐:

利用反射机制获得JavaBean的属性,然后生成一个XML文件.

//XmlFrame.java
package xmlgen.gui;


import java.awt.*;
import javax.swing.*;

public class XmlFrame extends JFrame{
 public XmlFrame(){
  this.setTitle("Xml Generator");
  
  Toolkit kit=Toolkit.getDefaultToolkit();
  Dimension d=kit.getScreenSize();
  int width=d.width;
  int height=d.height;
  
  this.setLocation((width-800)/2,(height-600)/2);  
  this.setSize(800,600);
  this.setContentPane(new XmlPanel());  
  
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  this.show(); 
 }
 public static void main(String[] args){
  new XmlFrame();
 }
}

//XmlPanel.java

package xmlgen.gui;


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.*;
import xmlgen.core.*;


public class XmlPanel extends JPanel{
 private JPanel midPane,classPane,propertyPane,elementPane;
 private JPanel xmlPane;
 private JTextArea xmlContent;
 private JTextField txtPackage,txtClass,txtRoot,txtElement,txtProperty;
 private JLabel lblPackage,lblClass,lblRoot,lblElement;
 private JButton btnClass,btnDelPro,btnAddElement,btnDelElement,btnGen;
 private JList lstClass,lstXml;
 private DefaultListModel lmClass,lmXml;
 

 private void init(){
  this.setLayout(new BorderLayout());
 
       
  classPane=new JPanel();
  classPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("类全名"),
            BorderFactory.createEmptyBorder(5,5,5,5)));
        this.lblPackage=new JLabel("类包名:");
        this.lblClass=new JLabel("类名:");
        this.txtPackage=new JTextField(20);
        this.txtClass=new JTextField(20);       
        this.btnClass=new JButton("获得属性");
        this.btnClass.setEnabled(false);
        this.btnClass.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
          String fullName=txtPackage.getText().trim()+"."+txtClass.getText().trim();
          Class c=null;
          xmlContent.setText("");
          lmClass.clear();
          try{
           c=Class.forName(fullName);
          }          
          catch(ClassNotFoundException ex){
           xmlContent.setText("找不到指定的类,请确保环境变量设置正确");
           return;
          }
          java.util.List list=Generator.getProperties(c);
          
          for(int i=0;i<list.size();i++)
           lmClass.addElement(list.get(i));
          if(lmClass.size()==0)
           xmlContent.setText("找不到任何属性");
         } 
        }
        );
       
       
        this.txtClass.getDocument().addDocumentListener(
         new AddTextListener(this.btnClass));
               
        classPane.add(this.lblPackage);
        classPane.add(this.txtPackage);
        classPane.add(this.lblClass);
        classPane.add(this.txtClass);
        classPane.add(this.btnClass);
           
        /*******************************************************************
         */
           
        propertyPane=new JPanel(new BorderLayout());
        propertyPane.setBorder(BorderFactory.createCompoundBorder(
         BorderFactory.createTitledBorder("Bean 属性"),
         BorderFactory.createEmptyBorder(5,5,5,5)));
        this.lmClass =new DefaultListModel();
        lmClass.addElement("这里是Bean的属性");
        lmClass.addElement("点击上面的按钮可以生成");
        lmClass.addElement("右边是XML中的属性");
        lmClass.addElement("可以删除不必要的");
        this.lstClass=new JList(this.lmClass);
        this.lstClass.addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent e) {
          if (e.getValueIsAdjusting() == false) {
               if (XmlPanel.this.lstClass.getSelectedIndex() == -1) {
               //No selection, disable fire button.
                  XmlPanel.this.btnDelPro.setEnabled(false);

               } else {
                //Selection, enable the fire button.
                  XmlPanel.this.btnDelPro.setEnabled(true);
              }
       }
       }
        }
        );
     
        JScrollPane sp1=new JScrollPane(this.lstClass);   
             
               
        this.btnDelPro=new JButton("删除属性");
        this.btnDelPro.setEnabled(false);
        this.btnDelPro.addActionListener(new DelPropertyListener());
        JPanel p1=new JPanel();
        p1.add(this.btnDelPro);
      
        propertyPane.add(sp1,BorderLayout.CENTER);
        propertyPane.add(p1,BorderLayout.SOUTH);
       
        /***************************************************************
         */
        elementPane=new JPanel(new BorderLayout());
        elementPane.setBorder(BorderFactory.createCompoundBorder(
         BorderFactory.createTitledBorder("XML 元素属性"),
         BorderFactory.createEmptyBorder(5,5,5,5)));
         
        this.lmXml=new DefaultListModel();
     
        this.lstXml=new JList(this.lmXml);
        this.lstXml.addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent e) {
          if (e.getValueIsAdjusting() == false) {
               if (XmlPanel.this.lstXml.getSelectedIndex() == -1) {
               //No selection, disable fire button.
                  XmlPanel.this.btnDelElement.setEnabled(false);

               } else {
                //Selection, enable the fire button.
                  XmlPanel.this.btnDelElement.setEnabled(true);
              }
       }
       }
        }
        );
        
        JScrollPane sp2=new JScrollPane(this.lstXml);
        this.btnDelElement=new JButton("删除");
        this.btnDelElement.setEnabled(false);
        this.btnDelElement.addActionListener(new DelElementListener());
        
        this.txtProperty=new JTextField(15);
        this.btnAddElement=new JButton("添加");
        this.btnAddElement.setEnabled(false);
        this.btnAddElement.addActionListener(new AddElement());     
        
        this.txtProperty.getDocument().addDocumentListener(
         new AddTextListener(this.btnAddElement));        
          
        JPanel p2=new JPanel();
        p2.add(this.btnDelElement);
        p2.add(this.txtProperty);
        p2.add(this.btnAddElement);
        
        elementPane.add(sp2,BorderLayout.CENTER);
        elementPane.add(p2,BorderLayout.SOUTH);
         
       
        /***********************************************
         */
        xmlPane=new JPanel(new BorderLayout());
        xmlPane.setBorder(BorderFactory.createCompoundBorder(
         BorderFactory.createTitledBorder("生成的 XML"),
         BorderFactory.createEmptyBorder(5,5,5,5))); 
        this.xmlContent=new JTextArea(10,60);
        this.xmlContent.setEditable(false);
       
      
        this.lblRoot=new JLabel("根节点:");
        this.lblElement=new JLabel("子节点名称:");
        this.txtRoot=new JTextField("root",15);
        this.txtElement=new JTextField("item",15);
       
        this.btnGen=new JButton("生成XML");
        DocumentListener dl=new AddTextListener(this.btnGen);
        this.txtRoot.getDocument().addDocumentListener(dl);
        this.txtElement.getDocument().addDocumentListener(dl);
       
       
        this.btnGen.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
          String root=txtRoot.getText().trim();
          String element=txtElement.getText().trim();
          if(root.equals("")) root="root";
          if(element.equals("")) element="item";
          String[] rows=new String[lmClass.size()];
          for(int i=0;i<lmClass.size();i++)
           rows[i]=(String)lmClass.getElementAt(i);
          String[] pros =new String[lmXml.size()];
          for(int i=0;i<lmXml.size();i++)
              pros[i]=(String)lmXml.getElementAt(i);
          String s=Generator.generateXml(root,element,rows,pros);
          xmlContent.setText(s);            
         }
        }
        );
       
        JScrollPane sp3=new JScrollPane(this.xmlContent);
        JPanel p3=new JPanel();
        p3.add(this.lblRoot);
        p3.add(this.txtRoot);
        p3.add(this.lblElement);
        p3.add(this.txtElement);
        p3.add(this.btnGen);
       
       
       
        xmlPane.add(sp3,BorderLayout.CENTER);
        xmlPane.add(p3,BorderLayout.SOUTH);
       
       
              
     
        midPane=new JPanel(new GridLayout(1,1));
       
        midPane.add(propertyPane);
        midPane.add(elementPane);
       
        //this.makeSize();
       
        this.add(classPane,BorderLayout.NORTH);
        this.add(midPane,BorderLayout.CENTER);
        this.add(xmlPane,BorderLayout.SOUTH);
        //this.add(new JLabel("Fuck"),BorderLayout.NORTH);
       
 }
 public XmlPanel(){
  init(); 
 }
 
 
 
 
 class AddElement implements ActionListener{
  public void actionPerformed(ActionEvent e){
   String name =txtProperty.getText().trim();

            //User didn't type in a unique name...
            if (name.equals("") || lmXml.contains(name)) {
                Toolkit.getDefaultToolkit().beep();
                txtProperty.requestFocusInWindow();
                txtProperty.selectAll();
                return;
            }

            int index = lstXml.getSelectedIndex(); //get selected index
            if (index == -1) { //no selection, so insert at beginning
                index = 0;
            } else {           //add after the selected item
                index++;
            }

            lmXml.insertElementAt(name.trim(), index);
            //If we just wanted to add to the end, we'd do this:
            //listModel.addElement(employeeName.getText());

            //Reset the text field.
            txtProperty.requestFocusInWindow();
            txtProperty.setText("");

            //Select the new item and make it visible.
            lstXml.setSelectedIndex(index);
            lstXml.ensureIndexIsVisible(index);
  }
 } 
 
 class AddTextListener implements DocumentListener {
        private boolean alreadyEnabled = false;
        private JButton button;

        public AddTextListener(JButton button) {
            this.button = button;
        }

        //Required by DocumentListener.
        public void insertUpdate(DocumentEvent e) {
            enableButton();
        }

        //Required by DocumentListener.
        public void removeUpdate(DocumentEvent e) {
            handleEmptyTextField(e);
        }

        //Required by DocumentListener.
        public void changedUpdate(DocumentEvent e) {
            if (!handleEmptyTextField(e)) {
                enableButton();
            }
        }

        private void enableButton() {
            if (!alreadyEnabled) {
                button.setEnabled(true);
            }
        }

        private boolean handleEmptyTextField(DocumentEvent e) {
            if (e.getDocument().getLength() <= 0) {
                button.setEnabled(false);
                alreadyEnabled = false;
                return true;
            }
            return false;
        }
    }
   
    class DelPropertyListener implements ActionListener {
       
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int[] index = lstClass.getSelectedIndices();
            if(index.length==0) return;
            for(int i=index.length-1;i>=0;i--)
             lmClass.remove(index[i]);

            int size = lmClass.getSize();

            if (size == 0) { //Nobody's left, disable firing.
                btnDelPro.setEnabled(false);

            } else { //Select an index.
                //removed item in last position
                int pos=index[0]-1;
       if(pos<0) pos=0;
                lstClass.setSelectedIndex(pos);
                lstClass.ensureIndexIsVisible(pos);
            }
        }
    }
   
 class DelElementListener implements ActionListener {
       
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int[] index = lstXml.getSelectedIndices();
            if(index.length==0) return;
            for(int i=index.length-1;i>=0;i--)
             lmXml.remove(index[i]);

            int size = lmXml.getSize();

            if (size == 0) { //Nobody's left, disable firing.
                btnDelElement.setEnabled(false);

            } else { //Select an index.
                //removed item in last position
                int pos=index[0]-1;
                if(pos<0) pos=0;
                lstXml.setSelectedIndex(pos);
                lstXml.ensureIndexIsVisible(pos);
            }
        }
    }
}

//Generator.java

package xmlgen.core;


import java.util.*;
import java.lang.reflect.*;
public class Generator{
 
 public static List getProperties(Class c){
     Method[] ms=c.getMethods();
     List list=new ArrayList();
     String mn="";
     String pro=""; 
     for(int i=0;i<ms.length;i++){
      if(ms[i].getParameterTypes().length!=0) continue;
      mn=ms[i].getName();
      if(mn.equals("getClass")) continue;
      if(mn.startsWith("get")&&mn.length()>3){
       pro=mn.substring(3,4).toLowerCase();
       if(mn.length()>4) pro+=mn.substring(4);
       list.add(pro);
      }
     }
     return list;
 }
 private static String crln="\r\n";
 public static String generateXml(String root,String element,String[] rows,String[] properties){
  //
  String pro="";
  for(int i=0;i<properties.length;i++){
   pro+=" "+properties[i]+"=\"\"";
  }
  String header="<"+element+" name=\"";
  
  
  
  StringBuffer sb=new StringBuffer(100);
  sb.append('<');
  sb.append(root);
  sb.append(">");
  sb.append(crln);
  
  
  for(int i=0;i<rows.length;i++){
   sb.append('\t');
   sb.append(header);
   sb.append(rows[i]);
   sb.append('\"');
   sb.append(pro);
   sb.append(" />");
   sb.append(crln);   
  }
  
  sb.append("</");
  sb.append(root);
  sb.append(">");
  return sb.toString();
 }
}

 

本文地址:http://com.8s8s.com/it/it13107.htm