第二篇、事件的监听


前言

上一篇我们共同学习了GUI编程的基础知识,本篇我们将继续学习GUI编程的事件监听。


一、事件监听

事件监听作为GUI编程中十分重要的一点,像点击按钮,光标悬停都属于事件,而事件监听就是当你做出需要做的事情后,后台需要做的后继动作,那么废话不多说我们直接上代码。

二、代码示例

1.按钮的事件监听

代码如下(示例):
TestActionEvent类

public class TestActionEvent {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(500,200,500,500);
        Button button = new Button();
        button.setSize(100,100);
        frame.add(button,BorderLayout.CENTER);
        frame.setVisible(true);
        //new一个事件监听器的对象
        MyActionListener myActionListener = new MyActionListener();
        //添加事件监听器
        button.addActionListener(myActionListener);
        //设置窗口可关闭
        WindowsClose(frame);

    }
    public static void WindowsClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

MyActionListener类

class MyActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("ddd");
    }
}

运行结果:
点击按钮输出字符
在这里插入图片描述

2.多个按钮使用同一个监听器

代码如下(示例):
TestActionTwo类

public class TestActionTwo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(500,200,500,500);
        Button button = new Button("start");
        Button button1 = new Button("stop");
        //可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值、
        button.setActionCommand("startCommand");
        frame.add(button,BorderLayout.SOUTH);
        frame.add(button1,BorderLayout.NORTH);
        frame.setVisible(true);
        //new一个事件监听器的对象
        MyActionListener1 myActionListener1 = new MyActionListener1();
        //添加事件监听器
        button.addActionListener(myActionListener1);
        button1.addActionListener(myActionListener1);
    }
}

MyActionListener1类

class MyActionListener1 implements ActionListener {
    @Override
    //e.getActionCommand获得按钮信息
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand()+"按钮被点击了");
    }
}

运行结果:
点击按钮输出对应字符
在这里插入图片描述


总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值