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); } }
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);; } }
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(); } }
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"); } }
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),