简体   繁体   中英

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() . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM