您的位置:首页 > 其它

Swing getSource() 使用的注意事项

2015-11-09 19:41 351 查看
在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类型。

初学–有错误请 指出,谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swing