swing之JButton简单封装

View Code
 1 package com.copy.util;
 2 
 3 import java.awt.Color;
 4 import java.awt.event.ActionEvent;
 5 import java.awt.event.ActionListener;
 6 import java.lang.reflect.InvocationTargetException;
 7 import java.lang.reflect.Method;
 8 
 9 import javax.swing.JButton;
10 
11 public class ButtonHandler extends JButton{
12     private String name ;
13     private String method;
14     private Object obj;//组建所在窗体对象
15     
16     public ButtonHandler( Object obj, String name, String method) {
17         this.setText(name);
18         this.name = name;
19         this.method = method;
20         this.obj = obj;
21 //        this.setBackground(Color.green);
22         getMethodByName(name);
23     }
24     
25     public void setFontgroundColor(Color c){
26         this.setForeground(c);
27     }
28     public void  setBackgroundColor(Color c){
29         this.setBackground(c);
30     }
31     
32     public void getMethodByName(final String name){
33         
34             this.addActionListener(new ActionListener() {
35                 
36                 @Override
37                 public void actionPerformed(ActionEvent e) {
38                     
39                     try {
40                         Class objClass = obj.getClass();
41                         Method md;
42                         md = objClass.getMethod(method, null);
43                         md.invoke(objClass.newInstance(), null);
44                     } catch (SecurityException e1) {
45                         // TODO Auto-generated catch block
46                         e1.printStackTrace();
47                     } catch (IllegalArgumentException e1) {
48                         // TODO Auto-generated catch block
49                         e1.printStackTrace();
50                     } catch (NoSuchMethodException e1) {
51                         // TODO Auto-generated catch block
52                         e1.printStackTrace();
53                     } catch (IllegalAccessException e1) {
54                         // TODO Auto-generated catch block
55                         e1.printStackTrace();
56                     } catch (InvocationTargetException e1) {
57                         // TODO Auto-generated catch block
58                         e1.printStackTrace();
59                     } catch (InstantiationException e1) {
60                         // TODO Auto-generated catch block
61                         e1.printStackTrace();
62                     }
63                     
64                 }
65             });
66     }
67     
68 }

 

转载于:https://www.cnblogs.com/FCWORLD/archive/2012/09/12/2681581.html

你可能感兴趣的:(swing之JButton简单封装)