Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly create KeyEvent in Java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
            }
        });
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading