在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類型。
初學–有錯誤請 指出,謝謝