GUI 監聽事件
阿新 • • 發佈:2021-08-05
編寫程式碼 TestActionEvent測試類
package com.xiang.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(); Button button = new Button("btn1"); // 因為addActionListener 需要一個 ActionListener ,所以就構造了一個ActionListener MyActionListener listener = new MyActionListener(); button.addActionListener(listener); frame.add(button, BorderLayout.CENTER); frame.setVisible(true); frame.setBounds(400, 400, 400, 400); frame.setBackground(Color.yellow); WindowClose(frame); } //關閉窗體事件 private static void WindowClose(Frame frame) { frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } // ActionListener 事件監聽 class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println("MyActionListener"); } };