Reputation: 3
I want to make a game that loops through an array every 1 second and then when the 'x' key is pressed the array stops printing, and the next 'x' key press the array resumes from the current element and loops again. my game starts with x and if i press again it just prints every 1 second. how do i add functionality and keep track of cards in the deck
My program is in java frame
public class Game {
private JFrame frame;
public static String[] cards = { "Jack", "Queen", "King" };
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
Timer timer = new Timer();
window.frame.setVisible(true);
//timer for card loops
timer.schedule(new GoCards(cards), 0, 1000);
window.frame.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e)
{
char key = e.getKeyChar();
if(key == 'x')
{
//pause the timer and if i press again then resume timer
timer.cancel();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
class GoCards extends TimerTask
{
String[] deck;
public GoCards(String[] cards)
{
deck = cards;
}
public void run()
{
for(int i = 0; i < 3; i++)
{
Thread.sleep(1000);
System.out.println(deck[i]);
}
}
Upvotes: 0
Views: 262
Reputation: 285405
Yours is a Swing application, so no, don't use Thread.sleep(...)
, not unless you want to risk putting your entire GUI to sleep, and don't use a java.util.Timer
, since this does not work well with the Swing event thread. Instead you will want to use the tool best suited for the job -- a Swing Timer, aka javax.swing.Timer
. The Timer can be started by calling start()
on it and stopped simply by calling stop()
, and you set the delay in milliseconds in its constructor. Also, use of a KeyListener is risky as it won't work if anything, such as a JButton for instance, steals the focus. Better to use Key Bindings. You can find links to the Swing tutorials and other Swing resources here: Swing Info.
Upvotes: 1
Reputation: 21
You can make use of a timer such as wait
Thread.sleep(milliseconds);
Then keep track of each key press / iteration with a new counter n.
Checking for key presses would be a matter of simply handling them as they come in, or something as arbitrary as checking each iteration for any particular key.
Upvotes: 0