GUI事件监听
事件监听
理解:当某个事件发生得时候,需要干什么
import javax.swing.*; 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(); //因为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 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("aaa"); } }
创建得按钮,每次按下会输出aaa
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 TestActionEvent2 { public static void main(String[] args) { //两个按钮,实现同一个监听 //例如 开始 停止 Frame frame =new Frame("开始-停止"); Button button1=new Button("start"); Button button2=new Button("stop"); //可以显示得定义触发会返回得命令,如果不显示定义,则会是默认的值 //可以多个按钮只写一个监听类,看类里面的if button2.setActionCommand("button2-stop"); MyMonitor myMoitor=new MyMonitor(); frame.add(button1,BorderLayout.NORTH); frame.add(button2,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); button1.addActionListener(myMoitor); button2.addActionListener(myMoitor); //关闭窗口 windowClose(frame); } //关闭窗体得事件 private static void windowClose(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class MyMonitor implements ActionListener { @Override public void actionPerformed(ActionEvent e) { //e.getActionCommand()获得按钮的信息 System.out.println("按钮被点击:msg"+ e.getActionCommand()); //可以进行这样得操作 if(e.getActionCommand().equals("start")) { System.out.println("Welcome"); } else { System.out.println("Goodbye"); } } }
多个按钮,共享一个监听事件