GUI 2.4事件監聽
阿新 • • 發佈:2022-03-16
2.4 事件監聽
事件監聽:當某個事件發生的時候,幹什麼?
package com.GGp.lesson02; 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 TestActionEvent { public static void main(String[] args) { Frame frame = new Frame(); frame.setVisible(true); frame.setSize(300,300); //按下按鈕,觸發一些事件 Button button = new Button("button"); button.setSize(100,100); button.setBackground(Color.red); //因為addActionListener(),需要一個ActionListener, //所以才去構造一個ActionListener MyActionListener myActionListener = new MyActionListener(); button.addActionListener(myActionListener); frame.add(button); 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("你按了一次哦"); } }