我已经尝试了很多东西,但似乎没有任何效果。当我按下转义键时,谁能帮我退出这个程序?我对线程没有太多经验,所以这可能是我的一个缺点。
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main implements ActionListener {
public static boolean start = false;
public static void Start() {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("Choose Action:");
JLabel label2 = new JLabel("Hello");
JButton button1 = new JButton("Start");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
start = true;
System.out.println("Pressed");
while(start) {
robot.keyPress(KeyEvent.VK_W);
try{
Thread.sleep(1);
}
catch(Exception ex) {
}
robot.keyRelease(KeyEvent.VK_W);
try{
Thread.sleep(150);
}
catch(Exception ex) {
}
robot.keyPress(KeyEvent.VK_S);
try{
Thread.sleep(1);
}
catch(Exception ex) {
}
robot.keyRelease(KeyEvent.VK_S);
try{
Thread.sleep(150);
}
catch(Exception ex) {
}
robot.keyPress(KeyEvent.VK_A);
try{
Thread.sleep(1);
}
catch(Exception ex) {
}
robot.keyRelease(KeyEvent.VK_A);
try{
Thread.sleep(150);
}
catch(Exception ex) {
}
robot.keyPress(KeyEvent.VK_D);
try{
Thread.sleep(1);
}
catch(Exception ex) {
}
robot.keyRelease(KeyEvent.VK_D);
try{
Thread.sleep(150);
}
catch(Exception ex) {
}
}
}
} );
JButton button2 = new JButton("Exit");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start = false;
frame.dispose();
System.exit(0);
}
} );
frame.setTitle("Test");
frame.setSize(350, 100);
frame.setResizable(false );
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.add(label);
panel.add(button1);
panel.add(button2);
panel.add(label2, BorderLayout.SOUTH);
}
public static void main (String args[]) throws InterruptedException {
Start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
老实说,我在这里不知所措。提前感谢任何帮助。