java SWing事件调用的两种机制

来源:互联网 发布:史蒂夫纳什生涯数据 编辑:程序博客网 时间:2024/06/07 09:31
/*** java swing中事件调用的两种机制:* (一)响应机制* (二)回调机制*/package test;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SimpleListener implements ActionListener {    /*     * 利用该类来监听事件源产生的事件,利用响应机制     */    public void actionPerformed(ActionEvent e) {        String buttonName = e.getActionCommand();        if (buttonName.equals("按钮1"))            System.out.println("按钮1 被点击");    }}/** 利用该类来处理事件源产生的事件,利用回调机制*/class ButtonAction extends AbstractAction {    public void actionPerformed(ActionEvent e) {        System.out.println("按钮2 被点击");    }}public class ActionTest {    private static JFrame frame; // 定义为静态变量以便main使用    private static JPanel myPanel; // 该面板用来放置按钮组件    private JButton button1; // 这里定义按钮组件    private JButton button2;    public ActionTest() { // 构造器, 建立图形界面        // 新建面板        myPanel = new JPanel();        // 新建按钮        button1 = new JButton("按钮1"); // 新建按钮1        // 建立一个actionlistener让按钮1注册,以便响应事件        SimpleListener ourListener = new SimpleListener();        button1.addActionListener(ourListener);        button2 = new JButton();// 新建按钮2        // 建立一个ButtonAction注入按钮2,以便响应事件        ButtonAction action = new ButtonAction();        button2.setAction(action);        button2.setText("按钮2");        myPanel.add(button1); // 添加按钮到面板        myPanel.add(button2);    }    public static void main(String s[]) {        ActionTest gui = new ActionTest(); // 新建Simple1组件        frame = new JFrame("Simple1"); // 新建JFrame        // 处理关闭事件的通常方法        frame.addWindowListener(new WindowAdapter() {            public void windowClosing(WindowEvent e) {                System.exit(0);            }        });        frame.getContentPane().add(myPanel);        frame.pack();        frame.setVisible(true);    }}

来源:http://hi.baidu.com/dobodo/item/f6ed3173d226c547ef1e538d
原创粉丝点击