Home > Blockchain >  How to properly create KeyEvent in Java
How to properly create KeyEvent in Java

Time:09-30

I want to be able to end a program in Java when a button is clicked, so I thought this would work

package com.mycompany.audio;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class Audio {
    public static void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_A) {
            System.exit(0);
        }
    }
    public static void main(String[] args) {
        JFrame GUI = new JFrame();
        GUI.setSize(300, 300);
        GUI.setLayout(null);
        GUI.setVisible(true);
        KeyEvent e = new KeyEvent(GUI, 1, 20, 1, 65, 'A');
        for (int i = 0; i < 10000000; i  ) {
            keyPressed(e);
            System.out.println(i);
        }
    }
}

Apparently that just ends the program right away if the KeyEvent parameter matches the method parameter, I'm not sure how to properly create the KeyEvent, I want my program to end if I hit A

CodePudding user response:

You need to add listener.

Here is working example

public class Main {
    public static void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_A) {
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        JFrame GUI = new JFrame();
        GUI.setSize(300, 300);
        GUI.setLayout(null);
        GUI.setVisible(true);
        GUI.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                Main.keyPressed(e);
            }
        });
    }
}
  •  Tags:  
  • java
  • Related