zoukankan      html  css  js  c++  java
  • Java:ActionListener接口

    ActionListener动作事件监听器,当你在点击按钮时希望可以实现一个操作就得用到该接口了。

    ActionListener接口所在包

    ActionListener接口在event包中,即在开头引入该包。

    import java.awt.event.*;
    

    ActionListener接口使用方法

    该接口只用实现一个方法叫做actionPerformed(ActionEvent arg0)这个方法。这个方法就是你希望触发事件时程序要做什么。

    class ButtonListener/*这里你可以改名字*/ implements ActionListener {
    	public void actionPerformed(ActionEvent arg0) {
            /*content*/
    	}
    }
    

    但如果只写这一个ButtonListener类我们发现是无法在点击按钮时运行该方法的。呵呵,你还没有给按钮添加这个对象呢。记得要给按钮添加一个ActionListener的对象,即写如下代码。

    ButtonListener button_listener = new ButtonListener();
    button.addActionListener(button_listener);
    

    接下来如果你又想移除该对象了,就直接remove掉就行了

    button.removeActionListener(button_listener);
    

    最后再唠叨一句,ActionListener接口不仅仅适用与点击按钮时触发事件,还可以在文本框、密码框按回车时触发事件等等。

    代码

    package technology;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MyFirstActionListener extends JFrame {
    	final static long serialVersionUID = 1L;
    	Container container = getContentPane();
    	JButton button = new JButton("点击我");
    	
    	class ButtonListener implements ActionListener {
    		int x = 0;
    		
    		public void actionPerformed(ActionEvent arg0) {
    			MyFirstActionListener.this.button.setText("我被点机了" + (++x) + "次");
    		}
    	}
    	
    	public MyFirstActionListener()
    	{
    		super("JFrame窗体");
    		this.setBounds(200, 100, 200, 200);
    		button.addActionListener(new ButtonListener());
    		container.add(button);
    		this.setVisible(true);
    	}
    	
    	public static void main(String[] args)
    	{
    		new MyFirstActionListener();
    	}
    }
    

    效果图如下:

    在这里插入图片描述

  • 相关阅读:
    软考自查:面向对象设计
    软考自查:UML建模
    软考自查:数据库设计
    软考自查:数据流图(DFD)
    软考自查:多媒体基础知识
    .user.ini后门/上传黑名单绕过
    域渗透:钓鱼欺骗配合SMB重放攻击
    实现:ipc管道连接到远程计划任务种马
    实现:ipc命名管道连接
    实现:注册表的增删改查
  • 原文地址:https://www.cnblogs.com/000zwx000/p/12531697.html
Copyright © 2011-2022 走看看