完成一个按钮的事件处理程序,实现功能自拟,例如:改变窗口的背景颜色,改变按钮的位置等等
1 package ccc; 2 import java.awt.Color; 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 import javax.swing.*; 6 public class niu extends JFrame { 7 JFrame f; 8 JPanel p; 9 JButton b1; 10 JButton b2; 11 public niu(){ 12 f =new JFrame(); 13 p =new JPanel(); 14 b1 = new JButton("改变位置"); 15 b2 = new JButton("改变颜色"); 16 p.setLayout(null); //流布局 17 b1.setBounds(150,150,100,30); 18 b2.setBounds(150,100,100,30); 19 f.setSize(350,350); 20 f.add(p); 21 p.add(b1); 22 p.add(b2); 23 b1.addActionListener(new b1Action()); 24 b2.addActionListener(new b2Action()); 25 f.setVisible(true); 26 } 27 class b1Action implements ActionListener{ 28 29 public void actionPerformed(ActionEvent e) { 30 p.setBackground(Color.BLUE); 31 } 32 } 33 34 class b2Action implements ActionListener{ 35 36 public void actionPerformed(ActionEvent e) { 37 b2.setBounds(90,40,100,30); 38 } 39 } 40 public static void main(String[] args){ 41 42 new niu(); //调用函数 43 } 44 45 }