Is it possible in Java to make it so that when you press the same keyboard key, different actions take place. For example, when you press the VK_F key, the audio file was played, and when it was pressed again, it stopped. If possible, please give a sample code.
- 3Yes, it is possible - Alexey Shimansky
- 2the most primitive is the creation of the flag boolean play = false; each time you press play =! play, what will be the reverse value. your player is already tied to this flag - alexandr gaiduchok
|
2 answers
It is possible so:
JTextField textField = new JTextField(20); textField.addKeyListener(new KeyListener() { private boolean isPlayed = false; public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_F) { if (isPlayed) { // выключить } else { // включить } isPlayed = !isPlayed; } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }); |
Declare a variable
private static boolean runStop = false; Further in if else you write the necessary code
btn.setOnAction((event) -> { if (runStop == false) { runStop = true; //код для запуска } else { runStop = false; //код для остановки } } ); |