歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中ActionEvent不使用內部類

Java中ActionEvent不使用內部類

日期:2017/3/1 10:35:58   编辑:Linux編程

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]

  1. package com.han;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.JFrame;
  5. /**
  6. * This program shows mainly how to add the events to the buttons.
  7. * Normally we use the internal class, but this example does not use it.
  8. * Instead, it uses a bloc "actionPerformed" that enables a couple of buttons to call it.
  9. * To determine on which button the action event occurred, we use e.getSource().
  10. * @author han
  11. *
  12. */
  13. @SuppressWarnings("serial")
  14. public class SwingButtonEvents extends JFrame implements ActionListener{
  15. /*declare some variables*/
  16. Button btn1;
  17. Button btn2;
  18. Button btn3;
  19. Container c=getContentPane();
  20. /*the construct function*/
  21. public SwingButtonEvents(){
  22. setTitle("Action Event");
  23. setSize(200,150);
  24. setVisible(true);
  25. setDefaultCloseOperation(EXIT_ON_CLOSE);
  26. c.setLayout(new FlowLayout(FlowLayout.CENTER)); //use FlowLayout
  27. btn1=new Button("Yellow");
  28. btn2=new Button("Green");
  29. btn3=new Button("Exit");
  30. c.add(btn1);
  31. c.add(btn2);
  32. c.add(btn3);
  33. btn1.addActionListener(this); // 把事件聆聽者向btn1注冊
  34. btn2.addActionListener(this); // 把事件聆聽者向btn2注冊
  35. btn3.addActionListener(this); // 把事件聆聽者向btn3注冊
  36. }
  37. public static void main(String args[]){
  38. new SwingButtonEvents();
  39. }
  40. @Override
  41. public void actionPerformed(ActionEvent e){ //方法重寫
  42. Button btn=(Button) e.getSource(); // 取得事件源對象
  43. if(btn.equals(btn1)){ // 如果是按下btn1按鈕
  44. c.setBackground(Color.yellow); //背景顏色是在Container中改的!而不是在JFrame中改!
  45. }else if(btn==btn2){ // 如果是按下btn2按鈕
  46. c.setBackground(Color.green);
  47. }else{ // 如果是按下btn3按鈕
  48. System.exit(0);
  49. }
  50. }
  51. }
Copyright © Linux教程網 All Rights Reserved