Swing事件监听

简介: Swing事件监听

文章目录


今天学习javaSwing库,创建桌面应用的时候,突然发现有些按钮需要特定的功能响应,故来研究一番Swing的事件监听。


1. 初始代码架构

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Btn extends JFrame{
    public static void main(String []args){
        JFrame f = new JFrame("事件监听测试");
        f.setBounds(0,0,300,400);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        Container page = f.getContentPane();
        page.setLayout(new FlowLayout());
        JButton btn = new JButton("打印");
        page.add(btn);
        f.setVisible(true);
    }
}

  • 运行的结果

2. 新需求:想要点击按钮的时候在终端打印一行信息(比如"按钮被点击")

产品爸爸,提了新需求,不能实现也要创造办法实现的啦


2.1 中规中矩的写监听器

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Btn{
    public static void main(String []args){
        JFrame f = new JFrame("事件监听测试");
        f.setBounds(0,0,300,400);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        Container page = f.getContentPane();
        page.setLayout(new FlowLayout());
        JButton btn = new JButton("打印");
        /**
         * 事件监听的使用步骤:
         * 1. 创建监听听
         * 2. 将监听器注册到按钮上
         * 
         */
        btnListener bl = new btnListener();
        btn.addActionListener(bl);
        page.add(btn);
        f.setVisible(true);
    }
}
class btnListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            System.out.println("按钮被点击了----");
        }
    }

  • 点击按钮的结果

2.2 发现问题

中规中矩地实现监听器地话,发现要另外写一个类实现ActionListener 接口地方法,使得代码架构显得比较臃肿。


2.3 使用匿名内部类优化代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Btn{
    public static void main(String []args){
        JFrame f = new JFrame("事件监听测试");
        f.setBounds(0,0,300,400);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        Container page = f.getContentPane();
        page.setLayout(new FlowLayout());
        JButton btn = new JButton("打印");
        /**
         * 事件监听的使用步骤:
         * 1. 创建监听听
         * 2. 将监听器注册到按钮上
         * 
         */
        ActionListener bl = new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                System.out.println("匿名内部类优化----");
            }
        };
        btn.addActionListener(bl);
        page.add(btn);
        f.setVisible(true);
    }
}
class btnListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            System.out.println("按钮被点击了----");
        }
    }


2.4 优化完之后发现还是不是很优雅

因为每次监听都有重复代码

@Override
 public void actionPerformed(ActionEvent e){
     System.out.println("匿名内部类优化----");
 } 

2.5 使用Lambda表达式再优化

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Btn{
    public static void main(String []args){
        JFrame f = new JFrame("事件监听测试");
        f.setBounds(0,0,300,400);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        Container page = f.getContentPane();
        page.setLayout(new FlowLayout());
        JButton btn = new JButton("打印");
        /**
         * 事件监听的使用步骤:
         * 1. 创建监听听
         * 2. 将监听器注册到按钮上
         * 
         */
        // ActionListener bl = new ActionListener(){
        //     @Override
        //     public void actionPerformed(ActionEvent e){
        //         System.out.println("匿名内部类优化----");
        //     }
        // };
        // btn.addActionListener(bl);
        btn.addActionListener((e)->{
            System.out.println("使用Lambda表达式优化");
        });
        page.add(btn);
        f.setVisible(true);
    }
}
class btnListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            System.out.println("按钮被点击了----");
        }
    }
  • 结果

2.6 嗯嗯,现在需求实现了,来看看最终的代码吧

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Btn{
    public static void main(String []args){
        JFrame f = new JFrame("事件监听测试");
        f.setBounds(0,0,300,400);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        Container page = f.getContentPane();
        page.setLayout(new FlowLayout());
        JButton btn = new JButton("打印");
        btn.addActionListener((e)->{
            System.out.println("使用Lambda表达式优化");
        });
        page.add(btn);
        f.setVisible(true);
    }
}

3. 完结撒花


建议从最菜的版本阅读哟,有利于理解监听器的实现


4、 附ActionListener接口源码

/*
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package java.awt.event;
import java.util.EventListener;
/**
 * The listener interface for receiving action events.
 * The class that is interested in processing an action event
 * implements this interface, and the object created with that
 * class is registered with a component, using the component's
 * {@code addActionListener} method. When the action event
 * occurs, that object's {@code actionPerformed} method is
 * invoked.
 *
 * @see ActionEvent
 * @see <a href="https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html">How to Write an Action Listener</a>
 *
 * @author Carl Quinn
 * @since 1.1
 */
public interface ActionListener extends EventListener {
    /**
     * Invoked when an action occurs.
     * @param e the event to be processed
     */
    public void actionPerformed(ActionEvent e);
}

To Be continue ....

相关文章
|
存储 Java 图形学
【Java Swing】重绘基本实现
【Java Swing】重绘基本实现
123 0
|
数据可视化 Java 容器
Swing程序设计(2)JFrame窗体
Swing程序设计(2)JFrame窗体
182 0
|
Java 容器
Java Swing中的按钮和事件
Java Swing中的按钮和事件
|
设计模式 前端开发
|
数据安全/隐私保护
Swing组件(上)
Swing所有组件都继承自JComponent,主要有文本处理、按钮、标签、列表、面板、组合框、滚动条、滚动面板、菜单、表格和树等组件。
Swing组件(上)
Java_Swing中关于关闭窗口的方法
Java_Swing中关于关闭窗口的方法
831 0
Java_Swing中让窗口居中显示的方法(三种方法)
Java_Swing中让窗口居中显示的方法(三种方法)
654 0