How to pause/stop a running code in Java (Eclipse) by pressing a key

Viewed 71

Can anyone please tell me how to pause and how to stop a running program in Java by pressing a certain key on the keyboard? When pausing, I also want it to resume when hitting a certain key (for example the same key). What I don't want is a function to pause it temporary until a certain amount of time has passed or a function in the code to pause or stop it automatically. It should only pause/stop when I'm telling the program to do so by pressing a certain key.

If you need my code, it's something like this:

import org.jfugue.pattern.Pattern;
import org.jfugue.player.Player;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class playSong extends JFrame implements ActionListener
{
    Player player = new Player();
    Pattern voice_1 = new Pattern();

    voice_1.add([*A part of the song*]);
    voice_1.add([*Another part of the song. I separated it to make it more readable.*]);
    voice_1.add([*Another part of the song. See above.*]);
    [*And so on over quite a few lines until the song is finished*]

    [*I am doing the same with two other Patterns, voice_2 and voice_3.*]
    
    Pattern main_voice = new Pattern();
    main_voice.add(voice_1);
    main_voice.add(voice_2);
    main_voice.add(voice_3);
    main_voice.setTempo([*Chosen veloticity*]);


    [*Code to create a JFrame with a JPanel with a JButton called song*]

    song.setSize([*chosen width*], [*chosen height*]);

    song.addActionListener(e ->
    {
        player.play(main_voice);
    });
}
1 Answers

To pause code in Eclipse, you need to run the code through the debugger (instead of "Run As", select "Debug As" - which is also accessible through the button that looks like an insect). Once running, you'll see a yellow Pause button that you can press during execution of the code (or, you can set breakpoints on a line by double-clicking in the margin to the left of the line number).

Related