JAVA中ActionEvent不使用内部类

This program shows mainly how to add the events to the buttons. Normally we use the internal class, but this example does not use it. Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it. To determine on which button the action event occurred, we use e.getSource().

package com.han;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
/**
 * This program shows mainly how to add the events to the buttons.
 * Normally we use the internal class, but this example does not use it.
 * Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it.
 * To determine on which button the action event occurred, we use e.getSource().
 * @author han
 *
 */
@SuppressWarnings("serial")
public class SwingButtonEvents extends JFrame implements ActionListener{
	/*declare some variables*/
	Button btn1;
	Button btn2;
	Button btn3;
	Container c=getContentPane();
	/*the construct function*/
	public SwingButtonEvents(){
		setTitle("Action Event");
		setSize(200,150);
		setVisible(true);		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		c.setLayout(new FlowLayout(FlowLayout.CENTER)); //use FlowLayout
		btn1=new Button("Yellow");
		btn2=new Button("Green");
		btn3=new Button("Exit"); 
		c.add(btn1);
		c.add(btn2);
		c.add(btn3);	
		btn1.addActionListener(this); // 把事件聆听者向btn1注册
		btn2.addActionListener(this); // 把事件聆听者向btn2注册
		btn3.addActionListener(this); // 把事件聆听者向btn3注册
	}	
	public static void main(String args[]){ 		
		new SwingButtonEvents();		
	}
	@Override
	public void actionPerformed(ActionEvent e){ //方法重写
		Button btn=(Button) e.getSource(); // 取得事件源对象
		if(btn.equals(btn1)){ // 如果是按下btn1按钮
			c.setBackground(Color.yellow); //背景颜色是在Container中改的!而不是在JFrame中改!
		}else if(btn==btn2){ // 如果是按下btn2按钮
			c.setBackground(Color.green);
		}else{ // 如果是按下btn3按钮
			System.exit(0);
		}
	}
}


你可能感兴趣的:(java,Class,action,button,events,variables)