首页 > 代码库 > Java SE (3) 之 事件监听

Java SE (3) 之 事件监听

 1 package com.sun; 2 import java.awt.*; 3 import javax.swing.*; 4 import java.awt.event.*; 5 public class Demo_1_1 extends JFrame implements ActionListener{ 6  7     Mypanel mp; 8     public static void main(String[] args) { 9         // TODO Auto-generated method stub10         Demo_1_1  demo1 = new Demo_1_1();11         12     }13     public Demo_1_1() {14          mp = new Mypanel();15         JButton jb1 = new JButton("Button");16         JButton jb2 = new JButton("Button2");17         jb1.addActionListener(this);18         jb1.setActionCommand("kaishi");19         jb2.addActionListener(this);20         jb2.setActionCommand("jieshu");21         this.add(mp);22         this.add(jb1,BorderLayout.EAST);23         this.add(jb2,BorderLayout.NORTH);24         // TODO Auto-generated constructor stub25         this.setTitle("demo");26         this.setSize(300,300);27         this.setLocation(40, 40);28         this.setDefaultCloseOperation(EXIT_ON_CLOSE);29         this.setVisible(true);30     }31     public void actionPerformed(ActionEvent e) {32         // TODO Auto-generated method stub33         if(e.getActionCommand().equals("kaishi")){34               System.out.println("this is yes ");35               mp.setBackground(Color.BLUE);36             37         }else if(e.getActionCommand().equals("jieshu")) {38              System.out.println("this is no ");39              mp.setBackground(Color.BLACK);40         }41     }42 }43 class Mypanel extends JPanel{44     45     public void paint(Graphics g){        46         super.paint(g);47             g.fillRect(0, 0, 300, 300);48             g.setColor(Color.YELLOW);49             g.fillRect(40, 40, 50, 50);50     }51 }