本文共 1253 字,大约阅读时间需要 4 分钟。
package com.lddx.day0306;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;//类本身实现ActionListenerpublic class TestActionListener2 implements ActionListener{ public static void main(String[] args) { TestActionListener2 test2=new TestActionListener2(); test2.init(); } public void init(){ JFrame f=new JFrame(); JPanel p=new JPanel(); JButton btn=new JButton("你好"); JButton btn1=new JButton("OK"); JButton btn2=new JButton("Cancel"); //this 表示当前类本身 btn.addActionListener(this); //匿名类 ActionListener ac=new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("okkkkkkk!"); } }; //使用匿名类对按钮绑定事件监听 btn1.addActionListener(ac); //方法2 btn2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("good bye!"); } }); p.add(btn); p.add(btn1); p.add(btn2); f.add(p); f.setSize(400, 500); f.setLocation(300, 100); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //重写父接口ActionListener中的方法 public void actionPerformed(ActionEvent e) { System.out.print("啥也不是!\n"); } }
转载地址:http://fsklf.baihongyu.com/