java实例化代码------------------监听事件

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.   
  5. public class ButtonTest  
  6. {  
  7.     public static void main(String args[])  
  8.     {  
  9.         ButtonFrame frame = new ButtonFrame();  
  10.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  11.         frame.setVisible(true);  
  12.     }  
  13. }  
  14.   
  15. class ButtonFrame extends JFrame  
  16. {  
  17.     public ButtonFrame()  
  18.     {  
  19.         setTitle("Button Test");  
  20.         setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  
  21.           
  22.           
  23.         ButtonPanel panel = new ButtonPanel();  
  24.         add(panel);  
  25.     }  
  26.       
  27.     public static final int DEFAULT_WIDTH = 800;  
  28.     public static final int DEFAULT_HEIGHT = 500;  
  29. }  
  30.   
  31. class ButtonPanel extends JPanel  
  32. {  
  33.     public ButtonPanel()  
  34.     {  
  35.         //定义button  
  36.         JButton yellowButton = new JButton("yellow");  
  37.         JButton blueButton = new JButton("blue");  
  38.         JButton redButton = new JButton("red");  
  39.           
  40.         //添加button到面板  
  41.         add(yellowButton);  
  42.         add(blueButton);  
  43.         add(redButton);  
  44.       
  45.         //创建按钮动作  
  46.         ColorAction yellowAction = new ColorAction(Color.YELLOW);  
  47.         ColorAction blueAction = new ColorAction(Color.BLUE);  
  48.         ColorAction redAction = new ColorAction(Color.RED);  
  49.           
  50.         //关联按钮与动作  
  51.         yellowButton.addActionListener(yellowAction);  
  52.         blueButton.addActionListener(blueAction);  
  53.         redButton.addActionListener(redAction);  
  54.     }  
  55.   
  56.     private class ColorAction implements ActionListener  
  57.     {  
  58.         public ColorAction(Color c)  
  59.         {  
  60.             backgroundColor = c;  
  61.         }  
  62.           
  63.         public void actionPerformed(ActionEvent event)  
  64.         {  
  65.             setBackground(backgroundColor);  
  66.         }  
  67.           
  68.         private Color backgroundColor;  
  69.     }  
  70. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值