[英]How to intercept a keypress in a Java application?
I'm creating a program that prints the sound of three bells. 我正在创建一个打印三个钟声的程序。 I need to stop the process when the user types a key on the keyboard, how can I do?
用户在键盘上键入键时,我需要停止该过程,该怎么办? Also, I would make sure that every bell show your sound in a random time, making use of the property
Math.random()
. 另外,我将使用
Math.random()
属性来确保每个钟声在随机时间内显示您的声音。 You can associate a random time to a thread? 您可以将随机时间关联到线程吗?
package campane;
import java.io.*;
import java.util.*;
public class GestioneCampane extends Thread {
public static void main(String [] args) {
BufferedReader tast = new BufferedReader(new InputStreamReader(System.in));
char pressione;
Campane campana = new Campane("DIN", 300);
Campane campana2 = new Campane("DON", 1000);
Campane campana3 = new Campane("DAN", 2000);
campana.start();
campana2.start();
campana3.start();
}
}
this is the second class 这是第二节课
package campane;
public class Campane extends Thread {
private String campane; // word to print
private int delay;
public Campane(String whatToSay, int delayTime) {
campane = whatToSay;
delay = delayTime;
}
public void run() {
try {
while(true) {
System.out.print(campane + " ");
Thread.sleep(delay);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You can stop a thread by interrupting it: 您可以通过中断线程来停止线程:
Thread.interrupt()
You can stop a thread for a given time, and continue with it after the time is consumed: 您可以在给定的时间内停止线程,并在消耗时间后继续执行该线程:
Long time = 15000L; // in milliseconds
Thread.sleep(time);
Use KeyBindings to intercept keys pressed and randomize your sound relevence, this example can save time 使用KeyBindings拦截按下的按键并随机化声音相关性, 此示例可以节省时间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.