ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java:ActionListener接口

2020-03-20 14:51:08  阅读:258  来源: 互联网

标签:ButtonListener Java button ActionListener 接口 按钮 public


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

效果图如下:

在这里插入图片描述

标签:ButtonListener,Java,button,ActionListener,接口,按钮,public
来源: https://www.cnblogs.com/000zwx000/p/12531697.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有