Swing getSource()の使用上の注意点

4653 ワード

SwingではawtEventのgetSource()が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();
    }
}

ボタンが1つしかない場合、ボタンをクリックするとイベントソースが1つしかないので、イベントがどれなのかを分解する必要はありません.2つのボタンがある場合:
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タイプに強く切り替える必要があります.
初学–間違いがあったら指摘してください.ありがとうございます.