简单实现java代理(2)

 
 
 
  
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

public class CancelListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent e)
	{
		JOptionPane.showMessageDialog(null, "Cancel");
	}

}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

public class OkListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent e)
	{
		JOptionPane.showMessageDialog(null, "OK");
	}

}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ButAction {
   public String value();
}

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Demo01 extends JFrame {
	@ButAction("com.part4.OkListener")
	private JButton ok=new JButton("OK");
	@ButAction("com.part4.CancelListener")
	private JButton cancel=new JButton("Cancel");
   public Demo01()
   {
	   super("demo01");
	   this.setSize(600, 400);
	   this.setLocation(100, 100);
	   this.setLayout(new FlowLayout());
	   this.add(ok);
	   this.add(cancel);
	   
	   this.setVisible(true);
	   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	   this.apt();
   }
   //解析Annotaion
   public void apt()
   {
	   Class clazz=this.getClass();
	   Field all[]=clazz.getDeclaredFields();
	   for(Field f:all)
	   {
		  if(f.getType()==JButton.class)
		  {
			  Annotation ano=f.getDeclaredAnnotation(ButAction.class);
			  if(null!=ano&&ano instanceof ButAction)
			  {
				  ButAction ba=(ButAction)ano;
				  String values=ba.value();
				 try {
					Class lisclass= Class.forName(values);
					JButton tem=(JButton)f.get(this);
					tem.addActionListener((ActionListener) lisclass.newInstance());
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			  }
		  }
	   }
   }
   
   
	public static void main(String[] args) {
		 new Demo01();

	}

}



猜你喜欢

转载自blog.csdn.net/qq_39915116/article/details/80375951
今日推荐