AI智能
改变未来

GUI编程核心技术AWT——事件监听


GUI编程核心技术AWT——事件监听

一个按钮的事件监听

package com.wei.lesson02;import java.awt.*;import java.awt.event.*;//一个按钮的事件监听public class TestActionEvent {public static void main(String[] args) {Frame frame = new Frame();Button button = new Button(\"btn\");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() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});}}class MyActionListener implements ActionListener {//监听事件,当某个事件发生时,将要干什么@Overridepublic void actionPerformed(ActionEvent e) {System.out.println(\"aaa\");//按下按钮时,将会输出这个指令}}

多个按钮共享一个监听事件

package com.wei.lesson02;import java.awt.*;import java.awt.event.*;public class TestAction2 {public static void main(String[] args) {//多个按钮实现同一个监听事件//如果按下start按钮实现一个操作,按下stop按钮实现另一个操作Frame frame = new Frame();Button button1 = new Button(\"start\");Button button2= new Button(\"stop\");Button button3= new Button(\"sleep\");frame.add(button1,BorderLayout.EAST);frame.add(button2,BorderLayout.WEST);frame.add(button3,BorderLayout.CENTER);//给按钮设置一下信息,下面通过e可以拿到//如果没设置信息,则默认的输出按钮上的lablebutton1.setActionCommand(\"button1-start\");button2.setActionCommand(\"button2-stop\");button3.setActionCommand(\"啥也不干\");MyMonitor myMonitor = new MyMonitor();button1.addActionListener(myMonitor);button2.addActionListener(myMonitor);button3.addActionListener(myMonitor);frame.setVisible(true);frame.pack();windowClose(frame);}private static void windowClose(Frame frame){frame.addWindowListener(new WindowAdapter() {@Overridepublic 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()...}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » GUI编程核心技术AWT——事件监听