当前位置: 代码迷 >> 综合 >> java笔记 ActionListener
  详细解决方案

java笔记 ActionListener

热度:19   发布时间:2024-02-27 00:12:26.0
//Inner class 事件处理例一
import java.awt.*;
import java.awt.event.*;
import java.net.PortUnreachableException;
import javax.swing.*;class myButtonFrame extends Frame
{
    Button btn;myButtonFrame(String s){
    // 设置窗口setTitle(s);setSize(400, 400);// 创建按钮btn = new Button("Pick Me");add(btn);// 创立监听ButtonListener bt = new ButtonListener();ButtonListener1 bt1 = new ButtonListener1();ButtonListener2 bt2 = new ButtonListener2();// 绑定事件btn.addActionListener(bt);btn.addActionListener(bt1);btn.addActionListener(bt2);//setDefaultCloseOperation(EXIT_ON_CLOSE);setVisible(true);}private class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e)  // 重写接口里面的函数{
    System.out.println("why me?");}}private class ButtonListener1 implements ActionListener{
    public void actionPerformed(ActionEvent e){
    System.out.println("don't pick me anymore!");}}private class ButtonListener2 implements ActionListener{
    public void actionPerformed(ActionEvent e){
    System.out.println("sb");}}
}//主类
public class test
{
    public static void main(String args[]){
    myButtonFrame frm = new myButtonFrame("ActionEventTest");}
}

在这里插入图片描述
1.先创建组件
2.建立监听器 ButtonListener bt = new ButtonListener();
3.将监听器添加到组件中 btn.addActionListener(bt);
4.实现监听器接口,实现actionPerformed函数中要传入参数ActionEvent e

private class ButtonListener2 implements ActionListener{
    public void actionPerformed(ActionEvent e)  // 传入参数{
    System.out.println("sb");}}

如果是Frame,输出是绑定时间的顺序

如果是JFrame,就是倒着的顺序

//Inner class 事件处理例一
import java.awt.*;
import java.awt.event.*;
import java.net.PortUnreachableException;
import javax.swing.*;class myButtonFrame extends JFrame
{
    JButton btn;myButtonFrame(String s){
    // 设置窗口setTitle(s);setSize(400, 400);// 创建按钮btn = new JButton("Pick Me");add(btn);// 创立监听ButtonListener bt = new ButtonListener();ButtonListener1 bt1 = new ButtonListener1();ButtonListener2 bt2 = new ButtonListener2();// 绑定事件btn.addActionListener(bt);btn.addActionListener(bt1);btn.addActionListener(bt2);setDefaultCloseOperation(EXIT_ON_CLOSE);setVisible(true);}private class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e)  // 重写接口里面的函数{
    System.out.println("why me?");}}private class ButtonListener1 implements ActionListener{
    public void actionPerformed(ActionEvent e){
    System.out.println("don't pick me anymore!");}}private class ButtonListener2 implements ActionListener{
    public void actionPerformed(ActionEvent e){
    System.out.println("sb");}}
}//主类
public class test
{
    public static void main(String args[]){
    myButtonFrame frm = new myButtonFrame("ActionEventTest");}
}

在这里插入图片描述

  相关解决方案