How can I start/stop a stop watch with only the spacebar? <p>I want to start/stop a stop watch only using the spacebar. I already made the KeyListeners, and that they only get activated when you press/release the spacebar.</p> <p>What I tried so far:</p> <p>I tried creating a stopwatch class, which SHOULD calculate the time difference between me pressing space for the first time, and second time. I tried it as follows:</p> <pre><code> public class Stopwatch { public Stopwatch(int i) { long time = System.currentTimeMillis(); if(i%2==1){ System.out.println("Timer Started at: " + time); }else{ System.out.println("Timer stopped at: " + System.currentTimeMillis()); System.out.println("Time diff: " + (time - System.currentTimeMillis())); } }} </code></pre> <p><code>int i</code> increases with every second spacebar press.</p> <p>I know the problem here is that everytime I start this class, <code>time</code> is getting reset to System.currentTimeMillis() because I only press Spacebar. Thus the difference is always 0.</p> <p>How can I change this so that I can somehow save the time I first pressed space?</p> <p>Here is the class with the Keylisteners. Ignore the Scrambler class, it has nothing to do with my Problem.</p> <pre><code> import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; public class StoppuhrFrame extends JFrame { JLabel time, scramble; public StoppuhrFrame() { time = new JLabel("00:00:00"); time.setBounds(162, 45, 325, 80); time.setFont(new Font("Arial", 100, 80)); add(time); scramble = new JLabel("Scramble: "); scramble.setBounds(165, 15, 370, 16); add(scramble); //Scrambler scrambler = new Scrambler(scramble); addKeyListener(new timer()); setTitle("Cube Timer"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setSize(650, 270); setVisible(true); } int i = 1; public class timer implements KeyListener { @Override public void keyPressed(KeyEvent keyEvent) { if(keyEvent.getKeyCode()==32){ new Stopwatch(i); i++; } @Override public void keyReleased(KeyEvent arg0) { if (arg0.getKeyCode() == 32) { if(i%2==0){ //new Scrambler(scramble); } } } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }} </code></pre> <p>Thanks in advance.</p>