JAVA中ActionEvent不使用内部类
2012-01-02 01:59
465 查看
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().
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.awt.event.ActionEvent 等的使用
- 使用OnTouchListener()的一个坑,监听不到MotionEvent.ACTION_UP
- java匿名内部类使用外部变量时,外部变量必须是final,为什么?
- java中内部类的使用
- java 四种内部类 使用细节(含代码)
- java语言基础(46)——内部类概述及使用
- android多点触控统一的原理(使用 event.getAction()&MotionEvent.ACTION_MASK的原因)
- Java 内部类种类及使用解析
- Java中使用匿名内部类创建多线程的3种方式
- 最安全的单例模式--java使用内部类实现单例模式
- java使用内部类的好处及其初始化
- JAVA中对同一问题分别使用内部类与匿名内部类实现
- Java 内部类的使用!
- Java 内部类,多线程中Synchronized与wait,notify的使用
- java关于内部类的一些使用跟限制记录
- java中传中文直接Action处理不使用加密处理
- java中的内部类与匿名类的基本使用方法
- Java中内部类的使用
- Java 内部类种类及使用解析
- Java 内部类种类及使用解析