package demo.event.swing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EventSourseTest {
public static void main(String[] args) {
new EventSourse();
}
}
class EventSourse extends SupperJFarme {
public EventSourse() {
super();
this.setTitle("事件源窗体改变");
add(new EventButtonJpanel());
}
}
class EventButtonJpanel extends JPanel implements ActionListener{
JButton yellow=null;
JButton red=null;
JButton green=null;
public EventButtonJpanel() {
yellow=new JButton("yellow");
red=new JButton("red");
green=new JButton("green");
yellow.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
this.add(yellow);
this.add(red);
this.add(green);
}
//此两种方法均可以做到相同的事情,唯一美中不足,在面板有很多的按钮,会有很多的if... 对于维护增减了新的按钮需要改动源程序
public void actionPerformed(ActionEvent e) {
//事件源返回的是一个对象,第一种
/**Object source=e.getSource();
if(source.equals(yellow))
this.setBackground(Color.yellow);
else if(source.equals(red))
this.setBackground(Color.red);
else if(source.equals(green))
this.setBackground(Color.GREEN);*/
//第二种,返回的是执行的命令的文本
String text=e.getActionCommand();
System.out.println(text);
if(text.equals("yellow"))
this.setBackground(Color.yellow);
else if(text.equals("red"))
this.setBackground(Color.red);
else if(text.equals("green"))
this.setBackground(Color.GREEN);
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EventSourseTest {
public static void main(String[] args) {
new EventSourse();
}
}
class EventSourse extends SupperJFarme {
public EventSourse() {
super();
this.setTitle("事件源窗体改变");
add(new EventButtonJpanel());
}
}
class EventButtonJpanel extends JPanel implements ActionListener{
JButton yellow=null;
JButton red=null;
JButton green=null;
public EventButtonJpanel() {
yellow=new JButton("yellow");
red=new JButton("red");
green=new JButton("green");
yellow.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
this.add(yellow);
this.add(red);
this.add(green);
}
//此两种方法均可以做到相同的事情,唯一美中不足,在面板有很多的按钮,会有很多的if... 对于维护增减了新的按钮需要改动源程序
public void actionPerformed(ActionEvent e) {
//事件源返回的是一个对象,第一种
/**Object source=e.getSource();
if(source.equals(yellow))
this.setBackground(Color.yellow);
else if(source.equals(red))
this.setBackground(Color.red);
else if(source.equals(green))
this.setBackground(Color.GREEN);*/
//第二种,返回的是执行的命令的文本
String text=e.getActionCommand();
System.out.println(text);
if(text.equals("yellow"))
this.setBackground(Color.yellow);
else if(text.equals("red"))
this.setBackground(Color.red);
else if(text.equals("green"))
this.setBackground(Color.GREEN);
}
}