Catherine_zhilin

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用Java实现按钮添加事件:

package HandEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class EventDemo extends JFrame {
    JPanel jp;
    JButton jb;
    public EventDemo() {
        jp=new JPanel();
        jb=new JButton("click me");
        add(jp);
        jp.add(jb);
        setSize(200,200);
        setVisible(true);
        //shixian sx=new shixian();//该类充当监视器
        jb.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent arg0) {
                System.out.print( "Let me give you a surprise.\n");
            }
            
        });
        
//        sx是实现类的对象
    }
    public  static void main(String args[]) {
        EventDemo ed=new EventDemo();
    }
}

运行后出现如下界面:

点击按钮“click me ”之后,在下面的运行结果框中出现“Let  me give you a surprise.”字样。点击一次 按钮 出现一次该字样。

以上是方法一,还有另外一种方法。

重新在下面创建一个class类:

package HandEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Testing extends JFrame {
    JPanel jp;
    JButton jb;
    public Testing() {
        jp=new JPanel();
        jb=new JButton("click me");
        add(jp);
        jp.add(jb);
        setSize(200,200);
        setVisible(true);
        shixian sx=new shixian();//该类充当监视器
        jb.addActionListener(new shixian());
        
//        sx是实现类的对象
    }
    public  static void main(String args[]) {
        Testing ed=new Testing();
    }
}

class shixian implements ActionListener{

    public void actionPerformed(ActionEvent arg0) {
        System.out.print( "Let me give you a surprise.\n");
    }
    
}

也能实现上面功能,但此方法并不推荐。

 

posted on 2017-12-02 22:37  kkkshiki  阅读(704)  评论(0编辑  收藏  举报