我希望能夠在單擊按鈕時結束 Java 程式,所以我認為這會起作用
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);
}
}
}
顯然,如果 KeyEvent 引數與方法引數匹配,則程式會立即結束,我不確定如何正確創建 KeyEvent,如果我點擊 A,我希望我的程式結束
uj5u.com熱心網友回復:
您需要添加偵聽器。
這是作業示例
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);
}
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/510519.html
標籤:爪哇