Java中ActionEvent不使用内部类

Linux大全评论391 views阅读模式

[Java]

  1. package com.han;  
  2. import java.awt.*;  
  3. import java.awt.event.*;  
  4. import javax.swing.JFrame;  
  5. /** 
  6.  * This program shows mainly how to add the events to the buttons. 
  7.  * Normally we use the internal class, but this example does not use it. 
  8.  * Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it. 
  9.  * To determine on which button the action event occurred, we use e.getSource(). 
  10.  * @author han 
  11.  * 
  12.  */  
  13. @SuppressWarnings("serial")  
  14. public class SwingButtonEvents extends JFrame implements ActionListener{  
  15.     /*declare some variables*/  
  16.     Button btn1;  
  17.     Button btn2;  
  18.     Button btn3;  
  19.     Container c=getContentPane();  
  20.     /*the construct function*/  
  21.     public SwingButtonEvents(){  
  22.         setTitle("Action Event");  
  23.         setSize(200,150);  
  24.         setVisible(true);         
  25.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
  26.         c.setLayout(new FlowLayout(FlowLayout.CENTER)); //use FlowLayout   
  27.         btn1=new Button("Yellow");  
  28.         btn2=new Button("Green");  
  29.         btn3=new Button("Exit");   
  30.         c.add(btn1);  
  31.         c.add(btn2);  
  32.         c.add(btn3);      
  33.         btn1.addActionListener(this); // 把事件聆听者向btn1注册   
  34.         btn2.addActionListener(this); // 把事件聆听者向btn2注册   
  35.         btn3.addActionListener(this); // 把事件聆听者向btn3注册   
  36.     }     
  37.     public static void main(String args[]){           
  38.         new SwingButtonEvents();          
  39.     }  
  40.     @Override  
  41.     public void actionPerformed(ActionEvent e){ //方法重写   
  42.         Button btn=(Button) e.getSource(); // 取得事件源对象   
  43.         if(btn.equals(btn1)){ // 如果是按下btn1按钮   
  44.             c.setBackground(Color.yellow); //背景颜色是在Container中改的!而不是在JFrame中改!   
  45.         }else if(btn==btn2){ // 如果是按下btn2按钮   
  46.             c.setBackground(Color.green);  
  47.         }else// 如果是按下btn3按钮   
  48.             System.exit(0);  
  49.         }  
  50.     }  
  51. }  

企鹅博客
  • 本文由 发表于 2020年8月15日 02:12:04
  • 转载请务必保留本文链接:https://www.qieseo.com/173762.html

发表评论