>  기사  >  Java  >  Java의 일반적인 이벤트 응답 방법 예 요약

Java의 일반적인 이벤트 응답 방법 예 요약

高洛峰
高洛峰원래의
2017-01-22 16:58:001363검색

이 문서의 예에는 컨테이너 클래스 모니터링, 리스너 클래스, AbstractAction, 리플렉션 등을 포함하여 Java의 일반적인 이벤트 응답 메서드가 요약되어 있습니다. 당신의 참고를 위해. 구체적인 방법은 다음과 같습니다.

먼저 Java 그래픽 사용자 인터페이스에서 이벤트를 처리하는 데 필요한 단계는 다음과 같습니다.

1 응답을 받아들이는 구성 요소(컨트롤)를 만듭니다. >2. 구현 관련 이벤트 청취 인터페이스
3. 이벤트 소스를 등록하는 액션 리스너
4. 이벤트가 트리거될 때 이벤트 처리

이에 따라 다음과 같은 중앙 집중식 방법을 통해 이벤트 응답이 이루어질 수 있습니다.

1. 컨테이너 클래스 모니터링


효과: 해당 응답 시간을 얻으려면 양식에서 세 개의 버튼을 클릭하세요.

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
  
//声明 类时,添加“implements ActionListener”实现监听的接口,如果要对多种监听方式进行监听,则用逗号间隔开 
// 比如“implements ActionListener,KeyListener” 
  
class ButtonListener extends JFrame implements ActionListener{ 
 JButton ok, cancel,exit; //创建接受响应的组建,就是三个按钮 
 public ButtonListener(String title){ 
 super(title); 
 this.setLayout(new FlowLayout()); 
 ok = new JButton("确定"); 
 cancel = new JButton("返回"); 
 exit = new JButton("退出"); 
//下面三个语句 为按钮分别 注册监听器 
 ok.addActionListener(this);   
 cancel.addActionListener(this); 
 exit.addActionListener(this); 
 getContentPane().add(ok); 
 getContentPane().add(cancel); 
 getContentPane().add(exit); 
} 
  
//完成 事件触发时的事件处理 
 public void actionPerformed(ActionEvent e){ 
   if(e.getSource()==ok) 
    System.out.println("确定"); 
   if(e.getSource()==cancel) 
    System.out.println("返回"); 
   if(e.getSource()==exit) 
     System.exit(0);; 
 } 
  
 public static void main(String args[]) { 
   ButtonListener pd=new ButtonListener("ActionEvent Demo"); 
   pd.setSize(250,100); 
  pd.setVisible(true); 
 } 
}

2. 모니터링 클래스 구현


효과: 양식에서 세 개의 버튼을 클릭하면 해당 응답 시간을 얻을 수 있습니다.

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
  
class ButtonListener1 extends JFrame { //这里没有实现监听 
 JButton ok, cancel,exit; 
 public ButtonListener1(String title){ 
  super(title); 
  this.setLayout(new FlowLayout()); 
  ok = new JButton("确定"); 
  cancel = new JButton("返回"); 
  exit = new JButton("退出"); 
  ok.addActionListener(new MyListener()); 
  cancel.addActionListener(new MyListener());; 
  exit.addActionListener(new MyListener());; 
  getContentPane().add(ok); 
  getContentPane().add(cancel); 
  getContentPane().add(exit); 
 } 
  
 public static void main(String args[]) { 
   ButtonListener pd=new ButtonListener("ActionEvent Demo"); 
   pd.setSize(250,100); 
  pd.setVisible(true); 
 } 
} 
  //监听动作事件 
class MyListener implements ActionListener{ 
  public void actionPerformed(ActionEvent e){ 
   if(e.getActionCommand()=="确定") 
    System.out.println("确定"); 
   if(e.getActionCommand()=="返回") 
    System.out.println("返回"); 
   if(e.getActionCommand()=="退出") 
     System.exit(0);; 
  } 
}

3. AbstractAction 클래스를 사용하여 모니터링

효과 달성: 메뉴를 클릭하고 응답

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JMenuItem; 
import javax.swing.JOptionPane; 
  
//此类继承AbstractAction,必须实现actionPerformed()方法。 
class AbstractEvent extends AbstractAction{ 
  //private static final long serialVersionUID = 1L; 
  AbstractEvent(){ 
  } 
  public void actionPerformed(ActionEvent e){ 
    //弹出确认对话框 
    if (e.getActionCommand()=="open"){ 
      JOptionPane.showMessageDialog(null, "打开"); 
    }else if (e.getActionCommand()=="close"){ 
      JOptionPane.showMessageDialog(null, "关闭"); 
    }else if (e.getActionCommand()=="run"){ 
      JOptionPane.showMessageDialog(null, "运行"); 
    }else if (e.getActionCommand()=="stop"){ 
      JOptionPane.showMessageDialog(null, "停止"); 
    } 
  } 
} 
public class TestAbstractEvent { 
  private static JMenuBar menubar; 
  private static JFrame frame; 
    
  //指定MenuEvent的具体处理程序是AbstractEvent类完成的。 
  final Action MenuEvent=new AbstractEvent(); 
  public TestAbstractEvent(){ 
    frame=new JFrame("menu"); 
    frame.getContentPane().setLayout(new BorderLayout()); 
    menubar=new JMenuBar(); 
    JMenu menuFile=new JMenu("file"); 
      
    //实例化一个菜单项,并添加监听openAction, 
    JMenuItem menuItemopen=new JMenuItem("open"); 
    menuItemopen.addActionListener(MenuEvent); 
    JMenuItem menuItemclose=new JMenuItem("close"); 
    menuItemclose.addActionListener(MenuEvent); 
    menuFile.add(menuItemopen); 
    menuFile.add(menuItemclose); 
    JMenu menuTool=new JMenu("tool"); 
    JMenuItem menuItemrun=new JMenuItem("run"); 
    menuItemrun.addActionListener(MenuEvent); 
    JMenuItem menuItemstop=new JMenuItem("stop"); 
    menuItemstop.addActionListener(MenuEvent); 
    menuTool.add(menuItemrun); 
    menuTool.add(menuItemstop); 
    menubar.add(menuFile); 
    menubar.add(menuTool); 
    menubar.setVisible(true); 
    frame.add(menubar,BorderLayout.NORTH); 
    frame.setSize(400,200); 
    frame.setVisible(true); 
  } 
  public static void main(String[] args){ 
    new TestAbstractEvent(); 
  } 
}

4. AbstractAction 클래스 + 반사 메서드


effect : 툴바에 있는 버튼 3개를 클릭하고, 버튼 이름을 통해 버튼과 동일한 이름의 클래스 구현 응답을 받습니다.

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import javax.swing.*; 
  
class ViewAction extends AbstractAction{ 
  private String ActionName=""; 
  //private JFrame frame=null; 
  private Action action=null; 
  public ViewAction(){ 
  } 
  public ViewAction(String ActionName){ 
    this.ActionName=ActionName; 
    //this.frame=frame; 
  } 
  @Override
  public void actionPerformed(ActionEvent e) { 
    Action action=getAction(this.ActionName); 
    action.execute(); 
  } 
  private Action getAction(String ActionName){ 
    try{ 
      if (this.action==null){ 
        Action action=(Action)Class.forName(ActionName).newInstance(); 
        this.action=action; 
      } 
      return this.action; 
    }catch(Exception e){ 
    return null; 
    } 
  } 
} 
public class TestAE extends JFrame { 
  public JToolBar bar=new JToolBar(); 
  String buttonName[]={"b1","b2","b3"}; 
  public TestAE(){ 
    super("事件"); 
    for (int i=0;i<buttonName.length;i++){ 
      ViewAction action=new ViewAction(buttonName[i]); 
      JButton button=new JButton(buttonName[i]); 
      button.addActionListener(action); 
      bar.add(button); 
    } 
    this.getContentPane().add(bar,BorderLayout.NORTH); 
    this.setSize(300, 200); 
    this.setLocationRelativeTo(null); 
    this.setVisible(true); 
  } 
  public static void main(String [] args){ 
    new TestAE(); 
  } 
} 
interface Action{ 
  void execute(); 
} 
class b1 implements Action{ 
  public void execute(){ 
    JOptionPane.showMessageDialog(null, "单击了 b1"); 
  } 
} 
class b2 implements Action{ 
  public void execute(){ 
    JOptionPane.showMessageDialog(null, "单击了 b2"); 
  } 
} 
class b3 implements Action{ 
  public void execute(){ 
    JOptionPane.showMessageDialog(null, "单击了 b3"); 
  } 
}

위의 예에는 더 자세한 설명이 포함되어 있어 이해하기 어렵지 않습니다. 이 기사에 설명된 예제가 모든 사람에게 도움이 되기를 바랍니다.

더 많은 Java 공통 이벤트 응답 방법 예제 및 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.