用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();
    }
}

运行后出现如下界面:

Java --UI添加事件

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

Java --UI添加事件

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

重新在下面创建一个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");
    }
    
}

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2021-05-27
相关资源
相似解决方案