通过一个小程序来学习通过不同的方式来实现事件处理。
这个小程序的作用是每点击一次按钮就生成一个按钮。效果:

第一种方式: (窗体直接实现相应的监听接口)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonDemo extends JFrame implements ActionListener
{
JPanel jp = new JPanel();
JButton jb = new JButton("Create Button");
private int count = 0;
public ButtonDemo()
{
this.add(jp);
jb.addActionListener(this);
jp.add(jb);
this.setTitle("Demo");
this.setBounds(300,100,400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
jp.add(new JButton("Button: " + (count++)));
this.setVisible(true); //是生成的按钮可见
}
public static void main(String[] args)
{
new ButtonDemo();
}
}
第二种方式:(自定义一个类,来实现相应的监听接口)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonDemo extends JFrame
{
JPanel jp = new JPanel();
JButton jb = new JButton("Create Button");
public ButtonDemo()
{
this.add(jp);
jb.addActionListener(new MyListener(this));
jp.add(jb);
this.setTitle("Demo");
this.setBounds(300,100,400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ButtonDemo();
}
}
class MyListener implements ActionListener //实现监听接口的自定义类
{
private int count = 0;
private ButtonDemo d;
MyListener(ButtonDemo d)
{
this.d = d;
}
public void actionPerformed(ActionEvent e)
{
d.jp.add(new JButton("Button: " + (count++)));
d.setVisible(true);
}
}
第三种方式:(使用匿名内部类实现相应的监听接口)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonDemo extends JFrame
{
JPanel jp = new JPanel();
JButton jb = new JButton("JButton");
private int count = 0;
public ButtonDemo()
{
this.add(jp);
jb.addActionListener(new ActionListener(){ //匿名内部类
public void actionPerformed(ActionEvent e)
{
jp.add(new JButton("The " + (count++)));
ButtonDemo.this.setVisible(true);
}
});
jp.add(jb);
this.setTitle("Demo");
this.setBounds(300,100,400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ButtonDemo();
}
}
摘自:杨军军的博客