前言
上一篇我们共同学习了GUI编程的基础知识,本篇我们将继续学习GUI编程的事件监听。
一、事件监听
事件监听作为GUI编程中十分重要的一点,像点击按钮,光标悬停都属于事件,而事件监听就是当你做出需要做的事情后,后台需要做的后继动作,那么废话不多说我们直接上代码。
二、代码示例
1.按钮的事件监听
代码如下(示例):
TestActionEvent类
public class TestActionEvent {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBounds(500,200,500,500);
Button button = new Button();
button.setSize(100,100);
frame.add(button,BorderLayout.CENTER);
frame.setVisible(true);
//new一个事件监听器的对象
MyActionListener myActionListener = new MyActionListener();
//添加事件监听器
button.addActionListener(myActionListener);
//设置窗口可关闭
WindowsClose(frame);
}
public static void WindowsClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
MyActionListener类
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ddd");
}
}
运行结果:
点击按钮输出字符
2.多个按钮使用同一个监听器
代码如下(示例):
TestActionTwo类
public class TestActionTwo {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBounds(500,200,500,500);
Button button = new Button("start");
Button button1 = new Button("stop");
//可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值、
button.setActionCommand("startCommand");
frame.add(button,BorderLayout.SOUTH);
frame.add(button1,BorderLayout.NORTH);
frame.setVisible(true);
//new一个事件监听器的对象
MyActionListener1 myActionListener1 = new MyActionListener1();
//添加事件监听器
button.addActionListener(myActionListener1);
button1.addActionListener(myActionListener1);
}
}
MyActionListener1类
class MyActionListener1 implements ActionListener {
@Override
//e.getActionCommand获得按钮信息
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand()+"按钮被点击了");
}
}
运行结果:
点击按钮输出对应字符