标签:void listener lang 取消 try one sage close lis
package com.woshi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
public class AnnotationTest {
private JFrame mainWin = new JFrame("使用注解绑定时间监听器");
@ActionListenerFor(listener = OkListener.class)
private JButton ok = new JButton("确定");
@ActionListenerFor(listener = CancelListener.class)
private JButton cancel = new JButton("取消");
public void init(){
//初始化界面的方法
JPanel jp = new JPanel();
jp.add(ok);
jp.add(cancel);
mainWin.add(jp);
ActionListenerInstaller.processAnnotations(this);
mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWin.pack();
mainWin.setVisible(true);
}
public static void main(String[] args) {
new AnnotationTest().init();
}
}
class OkListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(null,"单击了确认按钮");
}
}
class CancelListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent actionEvent) {
JOptionPane.showMessageDialog(null,"单击了取消按钮");
}
}
class ActionListenerInstaller{
public static void processAnnotations(Object o){
try {
Class cl = o.getClass();
for (Field field:cl.getDeclaredFields()){
field.setAccessible(true);
ActionListenerFor a = field.getAnnotation(ActionListenerFor.class);
Object fo = field.get(o);
if (a != null && fo != null && fo instanceof AbstractButton){
Class<? extends ActionListener> listenerClazz = a.listener();
ActionListener actionListener = listenerClazz.newInstance();
AbstractButton abstractButton = (AbstractButton)fo;
abstractButton.addActionListener(actionListener);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
图形页面 带 俩按钮 (是与注释、事件监听器相关的,但图形页面与其无关)
标签:void listener lang 取消 try one sage close lis
原文地址:https://www.cnblogs.com/woshi123/p/12535714.html