事件監聽(ActionListener)


事件監聽(ActionListener)

package com.zhang.Study.事件監聽;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ActionLister {
    public static void main(String[] args) {
        //創建事件監聽對象
        MyActionListener myActionListener = new MyActionListener();
        //創建一個窗口的基本操作
        Frame frame = new Frame();
        frame.setBounds(400,400,400,400);
        frame.setBackground(Color.red);
        frame.setVisible(true);

        //創建三個button對象
        Button button1=new Button("button1");
        Button button2=new Button("button2");
        Button button3=new Button("button3");
        //添加button對象
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        //把事件監聽對象傳入到button按鈕當中,當按下button按鈕,就會觸發監聽事件。
        button1.addActionListener(myActionListener);//兩個按鈕可以共用一個監聽事件
        button1.setActionCommand("button一");
//        public void setActionCommand(String command) {
//            actionCommand = command;
//        }
        // public String getActionCommand() {
//        return (actionCommand == null? label : actionCommand);
//    }源碼分析:如果沒有定義setActionCommand中的command,那么getActionCommand會返回label也就是
//     button按鈕label的值.如果有則返回定義的值。
        button2.addActionListener(myActionListener);
        //給窗口設置柵格布局
        frame.setLayout(new GridLayout(3,3));
        windowClose(frame);



    }
    //寫一個關閉窗口的方法,直接調用即可關閉窗口
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
 class MyActionListener implements ActionListener {
    //創建一個類實現監聽接口,並且重寫監聽接口的唯一方法


     @Override
     public void actionPerformed(ActionEvent e) {
         System.out.println("按鈕"+e.getActionCommand()+"被點擊了");
     }
 }

運行結果:

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM