java鍵盤監聽之視窗監聽的實現

qq_42885734發表於2020-10-08

一、程式碼

MainMethod.java(主函式方法)

package cn.lrt.program;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.security.Key;

class MainMethod extends Frame {

    KeyMonitorDemo keyMonitorDemo = new KeyMonitorDemo();

    public void launchedFrame() {

        this.setTitle("我是一個測試");
        this.setVisible(true);
        this.setSize(300,300);
        this.setLocation(300,300);

        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
               System.exit(0);
            }
        });

        this.addKeyListener(new KeyListener());

    }

    public static void main(String[] args) {

        MainMethod method = new MainMethod();
        method.launchedFrame();

    }


    class KeyListener extends KeyAdapter {

        public void keyPressed(KeyEvent e) {

            keyMonitorDemo.addDirection(e);

        }


        public void keyReleased(KeyEvent e) {

            keyMonitorDemo.minusDirection(e);

        }

    }

}

KeyMonitorDemo.java(鍵盤的監聽類)

package cn.lrt.program;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.security.Key;

class MainMethod extends Frame {

    KeyMonitorDemo keyMonitorDemo = new KeyMonitorDemo();

    public void launchedFrame() {

        this.setTitle("我是一個測試");
        this.setVisible(true);
        this.setSize(300,300);
        this.setLocation(300,300);

        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
               System.exit(0);
            }
        });

        this.addKeyListener(new KeyListener());

    }

    public static void main(String[] args) {

        MainMethod method = new MainMethod();
        method.launchedFrame();

    }


    class KeyListener extends KeyAdapter {

        public void keyPressed(KeyEvent e) {

            keyMonitorDemo.addDirection(e);

        }


        public void keyReleased(KeyEvent e) {

            keyMonitorDemo.minusDirection(e);

        }

    }

}

二、程式碼結構

在這裡插入圖片描述
三、執行截圖(這是按下鍵盤的時候才會響應的。up鍵、down鍵、right鍵、left鍵)
(1)視窗不中斷,監聽就不會停止。
在這裡插入圖片描述

相關文章