Java SE (3) 之 事件监听

时间:2024-07-29 11:36:50
 package com.sun;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo_1_1 extends JFrame implements ActionListener{ Mypanel mp;
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo_1_1 demo1 = new Demo_1_1(); }
public Demo_1_1() {
mp = new Mypanel();
JButton jb1 = new JButton("Button");
JButton jb2 = new JButton("Button2");
jb1.addActionListener(this);
jb1.setActionCommand("kaishi");
jb2.addActionListener(this);
jb2.setActionCommand("jieshu");
this.add(mp);
this.add(jb1,BorderLayout.EAST);
this.add(jb2,BorderLayout.NORTH);
// TODO Auto-generated constructor stub
this.setTitle("demo");
this.setSize(300,300);
this.setLocation(40, 40);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("kaishi")){
System.out.println("this is yes ");
mp.setBackground(Color.BLUE); }else if(e.getActionCommand().equals("jieshu")) {
System.out.println("this is no ");
mp.setBackground(Color.BLACK);
}
}
}
class Mypanel extends JPanel{ public void paint(Graphics g){
super.paint(g);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.YELLOW);
g.fillRect(40, 40, 50, 50);
}
}