Welcome 微信登录

首页 / 软件开发 / JAVA / Swing中的ActionListener响应研究

Swing中的ActionListener响应研究2011-01-06关于ActionListener的响应问题,就我的理解可以有两种方法。第一种就是你放到一个新的类里面,实现ActionListener接口,然后写好public void actionPerformed(ActionEvent e)的方法。这种当继承自JFrame还是蛮有用的,但是如果是一个在public static void main(String[] args)中建立一个JFrame,然后对里面的(比如按钮)实现监听,那么去实现ActionListener接口就不那么合适了(哎,很多都是当你做过后才知道什么是合适的),不过Java提供了另一种解决方案:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class ActionListenerTest ...{
public static void main(String[] args) ...{
JFrame frame = new JFrame("Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JButton jbClose = new JButton("Close the Frame");
jbClose.addActionListener(new ActionListener () ...{
public void actionPerformed(ActionEvent e) ...{
if (e.getSource().equals(jbClose)) ...{
System.exit(0);
}
}
}
);

frame.add(jbClose);
frame.pack();
frame.setVisible(true);
}
}