Home Java javaTutorial Summary of common event response method examples in Java

Summary of common event response method examples in Java

Jan 22, 2017 pm 04:58 PM

The examples in this article summarize common event response methods in Java, including container class monitoring, listener class, AbstractAction, reflection, etc. For your reference. The specific method is as follows:

First, in the Java graphical user interface, the necessary steps when processing events are:

1. Create a component (control) that accepts the response
2. Implementation Relevant event listening interface
3. Registering the action listener of the event source
4. Event processing when the event is triggered

Accordingly, the event response can be made through the following centralized method.

1. Container class monitoring

Effect: Click the three buttons in the form to achieve the corresponding response time.

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); 
 } 
}
Copy after login

2. Monitoring class implementation

Effect: Click three buttons in the form to achieve the corresponding corresponding time.

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);; 
  } 
}
Copy after login

3. Use the AbstractAction class to implement monitoring

Effect: click the menu and respond

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(); 
  } 
}
Copy after login

4. AbstractAction class + reflection method

Effect : Click three buttons on the toolbar, and through the name of the button, the response will be obtained by reflection using a class with the same name as the button.

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"); 
  } 
}
Copy after login

The above examples have more detailed comments and should not be difficult to understand. I hope the examples described in this article will be helpful to everyone.

For more java common event response method examples and related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles