Java基礎學習之Swing事件監聽

一、初始代碼架構

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

三、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" rel="external nofollow" >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);

}

到此這篇關於Java基礎學習之Swing事件監聽的文章就介紹到這瞭,更多相關Swing事件監聽內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: