1 package com.http; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 6 import javax.swing.*; 7 8 import com.http.TestSwing2.HelloWorldFrame; 9 10 public class SwingButton extends JFrame 11 { 12 private JPanel buttonPanel; 13 private static final int DEFAULT_WIDTH = 300; 14 private static final int DEFAULT_HEIGHT = 200; 15 16 public SwingButton() 17 { 18 setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); 19 //创建按钮 20 JButton yellowButton = new JButton("yellow"); 21 JButton blueButton = new JButton("blue"); 22 JButton redButton = new JButton("red"); 23 24 buttonPanel = new JPanel(); 25 26 //向面板中添加按钮 27 buttonPanel.add(yellowButton); 28 buttonPanel.add(blueButton); 29 buttonPanel.add(redButton); 30 31 //向frame中添加面板 32 add(buttonPanel); 33 34 //实例化事件 35 ColorAction ya = new ColorAction(Color.YELLOW); 36 ColorAction ba = new ColorAction(Color.BLUE); 37 ColorAction ra = new ColorAction(Color.RED); 38 39 //添加按钮事件,改变面板的颜色 40 yellowButton.addActionListener(ya); 41 blueButton.addActionListener(ba); 42 redButton.addActionListener(ra); 43 44 } 45 46 //触发后执行的事件,继承ActionListener,并重写actionPerformed接口 47 public class ColorAction implements ActionListener 48 { 49 50 private Color backgroundColor; 51 public ColorAction(Color c) 52 { 53 backgroundColor = c; 54 } 55 56 @Override 57 public void actionPerformed(ActionEvent event) { 58 // TODO Auto-generated method stub 59 buttonPanel.setBackground(backgroundColor); 60 } 61 } 62 63 public static void main(String[] argvs) 64 { 65 EventQueue.invokeLater(new Runnable() 66 { 67 public void run() 68 { 69 70 JFrame frame = new SwingButton(); 71 frame.setTitle("SwingButton"); 72 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 73 frame.setVisible(true); 74 } 75 }); 76 77 } 78 79 }