자바 사용자 정의 주 해 를 사용 하여 이벤트 원본 바 인 딩 이벤트 모니터 작업 예제 로 구현 합 니 다.
정의 주석
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 운행더 많은 자바 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있다.
본 고 에서 말 한 것 이 여러분 의 자바 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.