Swing getSource() 使用的注意事项

在Swing 中,awtEvent 中的getSourse()继承自EventObject,返回最初发生的Event的对象,也就是事件源。
例如:

import java.awt.event.*;
import java.awt.*;
public class frame extends Frame implements ActionListener
{
    Button  btn=new Button("退出1");
    public frame()
    {
         btn.setBackground(Color.orange);
         btn.setForeground(Color.RED);
         add(btn);
         setVisible(true);//设置窗口可见
         pack();
         btn.addActionListener(this);//添加监视器
    }
    public void actionPerformed(ActionEvent e)//动作事件的表现形式
    {
         //if(e.getSource()==btn)
         //{
              System.exit(0);
         //}
     }// TODO Auto-generated method stub
    public static void main(String args[])
    {
      frame smp=new frame();
    }
}

当只有一个按钮的时候,点击按钮只有一个事件源,因此可以不用分辨事件是哪个。
当有两个按钮的时候:

package day1021;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
class Dada extends JFrame implements ActionListener//实现ActionListener接口
{
    JButton  btn1;
    JButton  btn2;
    ActionListener listener;
    public Dada()
    {

         setLayout(new FlowLayout());
         btn1= new JButton("按钮1退出");
         add(btn1);
         btn2= new JButton("按钮2");
         add(btn2);
         btn1.addActionListener(this);//添加监视器
        btn2.addActionListener(this);//添加监视器
        setVisible(true);//设置窗口可见
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("getSource()");
        setBounds(100,100,310,260);
    }
    public void actionPerformed(ActionEvent e)//动作事件的表现形式
    {
         if((JButton)e.getSource()==btn1)//点击按钮1后程序退出
         {
              System.exit(0);
         }
         if((JButton)e.getSource()==btn2)//点击按钮2后输出一句话
         {
              System.out.println("哎哟,不错哦");
         }
    }
}

public class test1 
{

    public static void main(String args[])
    {
        Dada smp=new Dada() ;    
    }
}

由于getourse()返回最初发生的Event的对象,所以进行比较的时候需要强转为JButton类型。

初学–有错误请 指出,谢谢

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值