자바 사용자 정의 주 해 를 사용 하여 이벤트 원본 바 인 딩 이벤트 모니터 작업 예제 로 구현 합 니 다.

이 사례 는 자바 가 사용자 정의 주 해 를 사용 하여 이벤트 소스 바 인 딩 이벤트 모니터 작업 을 실현 하 는 것 을 보 여 줍 니 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
정의 주석

import java.lang.annotation.*;
import java.awt.event.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionListenerFor
{
  //         ,       
  //  listener              
  Class<? extends ActionListener> listener();
}

이 주해 처리 프로그램

import java.lang.reflect.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionListenerInstaller
{
  //   Annotation   ,  obj   Annotation   
  public static void processAnnotations(Object obj)
  {
   try
   {
     //   obj    
     Class cl = obj.getClass();
     //     obj         ,         
     for (Field f : cl.getDeclaredFields())
     {
      //               。
      f.setAccessible(true);
      //         ActionListenerFor   Annotation
      ActionListenerFor a = f.getAnnotation(ActionListenerFor.class);
      //       f  
      Object fObj = f.get(obj);
      //   f AbstractButton   , a  null
      if (a != null && fObj != null
         && fObj instanceof AbstractButton)
      {
        //   a    listner   (        )
        Class<? extends ActionListener> listenerClazz = a.listener();
        //        listner    
        ActionListener al = listenerClazz.newInstance();
        AbstractButton ab = (AbstractButton)fObj;
        //  ab         
        ab.addActionListener(al);
      }
     }
   }
   catch (Exception e)
   {
     e.printStackTrace();
   }
  }
}

삼 테스트 주해 프로그램

import java.awt.event.*;
import javax.swing.*;
public class AnnotationTest
{
  private JFrame mainWin = new JFrame("           ");
  //   Annotation ok         
  @ActionListenerFor(listener=OkListener.class)
  private JButton ok = new JButton("  ");
  //   Annotation cancel         
  @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();
  }
}
//   ok           
class OkListener implements ActionListener
{
  public void actionPerformed(ActionEvent evt)
  {
   JOptionPane.showMessageDialog(null , "       ");
  }
}
//   cancel           
class CancelListener implements ActionListener
{
  public void actionPerformed(ActionEvent evt)
  {
   JOptionPane.showMessageDialog(null , "       ");
  }
}

4 운행


더 많은 자바 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.
본 고 에서 말 한 것 이 여러분 의 자바 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기