day25

GUI

Frame
Frame f = new Frame("my frame");
f.setSize(300,200);
f.setLoction(300,150);
//f.setBounds(300,200,300,150);
f.setVisible(true);
Button bu = new Button("按钮");
f.add(bu);
//为窗体添加监听器
f.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
    System.out.println("closing");
    //Syetem.exit(0);退出系统
  }//关闭事件处理
});
  • //WindowAdapter(适配器)是一个匿名内部类,覆盖了addWindowLister抽象类的7个方法,而我们只需要覆盖WindowAdapter中我们需要的方法即可
  • 适配器的存在是为了更好的创建监听器对象,当监听器中的方法超过两个时,该监听器一般都有适配器
事件监听机制
ActionListener(活动监听器)
为按钮添加一个活动监听器,目的:一点击按钮程序关闭
bu.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e){
    //System.out.println("button run");
    System.exit(0);
  }
});
鼠标和键盘事件
public class MouseAndKeyDemo{
  private Frame f;
  private TextField tf;
  private Button b
  public MouseAndKeyDemo(){
    init();
  }
  private void init(){
    f = new Frame("演示键鼠监听器");
    f.setBounds(400,200,300,200);
    f.setLayout(new FlowLayout());
    tf = new TextField(15);
    b = new Button("anniu");
    f.add(b);
    f.add(tf);
    myevent();
    f.setVisible(true);
  }
  private void myevent(){
    //给文本框添加键盘监听
    tf.addKeyListener(new KeyAdapter(){
      public void keyPressed(KeyEvent e){
        System.out.println("key run"+KeyEvent.getKeyText(e.getKeyCode()));
      }
    });
    f.addActionListener(new WindowAdapter(){
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }
    });
    //添加一个鼠标监听
    b.addMouseListener(new  MouseAdapter(){
      private int count =1;
      public void mouseEntered(MouseEvent e){
        tf.setText("mouse enter:"+count++);
      }
      public void mouseClick(MouseEvent e){
        if(e.getClickCount()==2)
          tf.setText("mouse click:"+count++);
      }
    });
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值