Java图形化界面GUI:事件监听
事件监听:当某个事情发生的时候,干什么!
package com.zdz.gui; 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) { //Action1(); Action2(); } private static void Action1(){ //按下按钮触发一些事件 Frame frame = new Frame(); Button button = new Button(); //因为addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener MyActionListener myActionListener = new MyActionListener(); button.addActionListener(myActionListener); frame.add(button,BorderLayout.CENTER); frame.pack(); frame.setVisible(true); windowClose(frame); } private static void Action2(){ //两个按钮实现同一个监听 //开始 停止 Frame frame = new Frame(); Button button1 = new Button("start"); Button button2 = new Button("stop"); //set替代默认值 button1.setActionCommand("button1-stop"); MyMonitor myMonitor = new MyMonitor(); button1.addActionListener(myMonitor); button2.addActionListener(myMonitor); frame.add(button1,BorderLayout.NORTH); frame.add(button2,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); 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("aaaa"); } } class MyMonitor implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //e.getActionCommand()获得按钮信息 System.out.println("按钮被点击了 msg:"+e.getActionCommand()); if(e.getActionCommand().equals("button1-stop")){ System.out.println("button1被点击了"); }else { System.out.println("button2"); } } }