事件监听

1. 通过添加 addWindowListener 和 addActionListener 监听窗口的关闭事件和按钮的click事件。

  package com.langtao.base.demo3;

  import java.awt.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.awt.event.WindowAdapter;
  import java.awt.event.WindowEvent;
  import java.util.function.DoubleToIntFunction;

  public class Application {

      public static void main(String[] args) {

          Frame frame = new Frame();
          frame.setVisible(true);
          frame.setSize(300,400);
          frame.setBackground(Color.GRAY);
          frame.setLayout(new FlowLayout());

          Button btn1 = new Button("btn1");
          btn1.addActionListener(new myActionListener());

          frame.add(btn1);

          windowClose(frame);
      }


      public static void windowClose(Frame frame){
          frame.addWindowListener(new WindowAdapter() {
              @Override
              public void windowClosing(WindowEvent e) {
                  System.exit(0);
              }
          });
      }
  }

  class myActionListener implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
          System.out.println("Hello, you are clicking the button." + this.toString());
      }
  };
上一篇:java推箱子


下一篇:java飞机大战小游戏