This program shows mainly how to add the events to the buttons. Normally we use the internal class, but this example does not use it. Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it. To determine on which button the action event occurred, we use e.getSource().
[java]
- package com.han;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.JFrame;
- /**
- * This program shows mainly how to add the events to the buttons.
- * Normally we use the internal class, but this example does not use it.
- * Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it.
- * To determine on which button the action event occurred, we use e.getSource().
- * @author han
- *
- */
- @SuppressWarnings("serial")
- public class SwingButtonEvents extends JFrame implements ActionListener{
- /*declare some variables*/
- Button btn1;
- Button btn2;
- Button btn3;
- Container c=getContentPane();
- /*the construct function*/
- public SwingButtonEvents(){
- setTitle("Action Event");
- setSize(200,150);
- setVisible(true);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- c.setLayout(new FlowLayout(FlowLayout.CENTER)); //use FlowLayout
- btn1=new Button("Yellow");
- btn2=new Button("Green");
- btn3=new Button("Exit");
- c.add(btn1);
- c.add(btn2);
- c.add(btn3);
- btn1.addActionListener(this); // 把事件聆聽者向btn1注冊
- btn2.addActionListener(this); // 把事件聆聽者向btn2注冊
- btn3.addActionListener(this); // 把事件聆聽者向btn3注冊
- }
- public static void main(String args[]){
- new SwingButtonEvents();
- }
- @Override
- public void actionPerformed(ActionEvent e){ //方法重寫
- Button btn=(Button) e.getSource(); // 取得事件源對象
- if(btn.equals(btn1)){ // 如果是按下btn1按鈕
- c.setBackground(Color.yellow); //背景顏色是在Container中改的!而不是在JFrame中改!
- }else if(btn==btn2){ // 如果是按下btn2按鈕
- c.setBackground(Color.green);
- }else{ // 如果是按下btn3按鈕
- System.exit(0);
- }
- }
- }